我正在尝试使用 Spock 为我的 Spring Boot 1.4.0 编写一些测试,但我的 application-test-properties 文件没有被拾取。
我的 gradle 中有这个:
dependencies {
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile 'org.codehaus.groovy:groovy-all:2.4.1'
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.spockframework:spock-spring:1.0-groovy-2.4') {
}
然后我有这个
/src/test/groovy/资源:
# JWT Key
jwt.key=MyKy@99
最后是我的 Spock 测试:
@SpringBootTest(classes = MyApplication.class, webEnvironment=SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource("application-test.properties")
public class TokenUtilityTest extends Specification {
@Autowired
private TokenUtility tokenUtility
def "test a valid token creation"() {
def userDetails = new User(username: "test", password: "password", accountNonExpired: true, accountNonLocked: true,
);
when:
def token = tokenUtility.buildToken(userDetails)
then:
token != null
}
}
哪个正在测试这个类:
@Component
public class TokenUtility {
private static final Logger LOG = LoggerFactory.getLogger( TokenUtility.class );
@Value("${jwt.key}")
private String jwtKey;
public String buildToken(UserDetails user) {
return Jwts.builder()
.setSubject(user.getUsername())
.signWith(SignatureAlgorithm.HS512, jwtKey)
.compact();
}
public boolean validate(String token) {
try {
Jwts.parser().setSigningKey(jwtKey).parseClaimsJws(token);
return true;
} catch (SignatureException e) {
LOG.error("Invalid JWT found: " + token);
}
return false;
}
}
我最初在测试中实例化了 TokenUtility,但 application-test.properties 从未加载(我假设从那时起jwtKey为空)。所以我正在尝试 @Autowired 我的类正在测试,但现在它是空的。
看起来 Spring Boot 1.4 在测试方面做了很多改变,所以也许我没有正确连接?