【发布时间】:2016-11-27 10:33:47
【问题描述】:
我正在尝试使用 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/resources:
# 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 在测试方面发生了很大变化,所以也许我没有正确接线?
【问题讨论】:
标签: spring-boot spock spring-test