spring boot 1.4, spock and application.properties

6

我想为我的Spring Boot 1.4.0应用编写一些Spock测试,但是我的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,但是应用程序-test.properties从未被加载(我假设是因为jwtKey为空)。所以我尝试在我的测试类中使用@Autowired注入我的类,但现在它的值为null。

看起来Spring Boot 1.4对于测试方面进行了很多更改,所以也许我没有正确地进行连接?

2个回答

7

你的测试代码存在几个问题。首先,你的依赖项有问题-Spock 1.0不支持@SpringBootTest注释,因此不会初始化上下文或进行后处理,因此会出现空指针异常:没有自动装配。

该注释的支持在Spock 1.1中添加,但它仍然是候选发布版,因此你必须使用它:

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 group: 'io.jsonwebtoken', name: 'jjwt', version: '0.6.0'

    compile('org.codehaus.groovy:groovy')

    testCompile('org.springframework.boot:spring-boot-starter-test')
    testCompile('org.spockframework:spock-core:1.1-groovy-2.4-rc-1')
    testCompile('org.spockframework:spock-spring:1.1-groovy-2.4-rc-1')
    testCompile group: 'com.h2database', name: 'h2', version: '1.4.192'
}

那么,你的应用程序-test.properties的路径不正确,应该是 /application-test.properties,因为它在类路径的根目录下:

@SpringBootTest(classes = DemoApplication.class, 
                webEnvironment = WebEnvironment.RANDOM_PORT)
@TestPropertySource("/application-test.properties")
public class TokenUtilityTest extends Specification {

    @Autowired
    TokenUtility tokenUtility

    def "test a valid token creation"() {
        def userDetails = new User("test", "password", Collections.emptyList());

        when:
        def token = tokenUtility.buildToken(userDetails)

        then:
        token != null
    }
}

4

我曾经遇到过类似的问题,但是对于我来说,在使用Spock时,解决方法是将@Value注释中的双引号".."改为单引号'..'。请看下面的示例:

@Value('${jwt.key}')
private String jwtKey;

提示- 这不是问题的确切答案。我发布这篇文章是为了帮助那些遇到类似问题的人,并最终在此处找到了解决方法。


2
由于Spock使用Groovy,双引号被处理为GString,这类似于SpEL,因此Groovy尝试用实际变量替换占位符。这就是为什么需要使用单引号以避免Groovy查找变量的原因。 - rvazquezglez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接