【问题标题】:spring boot 1.4, spock and application.propertiesspring boot 1.4、spock 和 application.properties
【发布时间】: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


    【解决方案1】:

    您的测试代码有几个问题;首先,您的依赖项很糟糕 - 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'
    }
    

    那么,您的 application-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
        }
    }
    

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,但对我来说,解决方案是在使用Spock 时将@Value 注释内的双引号".." 更改为单引号'..'。请在下面找到示例:

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

      PS - 这不是问题的确切答案。我是为面临与我类似的问题并最终来到这里的人发布此消息的。

      【讨论】:

      • 由于 spock 使用 groovy,双引号被作为 GString 处理,这与 SpEL 类似,因此 groovy 尝试用真实变量替换占位符。这就是为什么需要使用单引号,以避免对变量进行常规查找。
      猜你喜欢
      • 2017-08-07
      • 2020-04-18
      • 2016-12-08
      • 2017-06-28
      • 1970-01-01
      • 2019-03-18
      • 2016-03-04
      • 2021-02-07
      • 2020-09-07
      相关资源
      最近更新 更多