【问题标题】:How to setup integration test with Spring and Spock?如何使用 Spring 和 Spock 设置集成测试?
【发布时间】:2016-06-18 08:23:26
【问题描述】:

我有一个项目,有 2 个模块,A 和 B(业务逻辑和休息服务),B 依赖于 A。

启动 SpringBoot 应用程序有效,但我无法正确设置集成测试。

我有一个扩展 Spock 规范的抽象类

@ContextConfiguration(loader = SpringApplicationContextLoader.class, 
                    classes = [WebAppConfig.class, AppConfig.class])
@WebIntegrationTest
@Stepwise
abstract class RestIntegrationBaseSpec extends Specification {

    RestTemplate restTemplate = new TestRestTemplate()

    String getBasePath() { "" }

    URI serviceURI(String path = "") {
        new URI("http://localhost:8080/${basePath}${path}")
    }
}

我为我的测试扩展它,尝试注入在模块 A 中实现的服务

class TransactionsControllerSpec extends RestIntegrationBaseSpec{

@Override
String getBasePath() {
    //return "api/"
    return ""
}

@Autowired
ImportService importService

def setupSpec() {
    initDB()
}

private void initDB() {
    importService.importData();
}

def "Test"() {
    given:
      ...
    when:
        ...
    then:
        ...
}

但我在 importService.importData() 上得到 NullPointerException,importService 为空。

在我的 B 项目的 gradle 文件中,我添加了这些依赖项:

compile('org.springframework.boot:spring-boot-starter-aop')
compile('org.springframework.boot:spring-boot-devtools')
compile('org.springframework.boot:spring-boot-starter-remote-shell')
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.projectlombok:lombok:1.16.6')
compile project(':business')

// http://mvnrepository.com/artifact/commons-fileupload/commons-fileupload
compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.2'

// http://mvnrepository.com/artifact/commons-io/commons-io
compile group: 'commons-io', name: 'commons-io', version: '2.5'

testCompile('org.springframework.boot:spring-boot-starter-test')

testCompile('org.spockframework:spock-core:1.0-groovy-2.4')
testCompile('org.spockframework:spock-spring:1.0-groovy-2.4')

我错过了什么?

【问题讨论】:

  • 你的意思是@Autowired?
  • @MattBusche 是的,错字,谢谢

标签: spring-boot integration-testing spock


【解决方案1】:

不确定这是否能解决问题,但请尝试在测试中添加 @WebAppConfiguration。这将确保为测试加载WebApplicationContext

【讨论】:

    猜你喜欢
    • 2017-06-28
    • 2014-08-15
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多