如何使用Spring和Spock设置集成测试?

时间:2016-06-18 08:23:27

标签: spring-boot integration-testing spock

我有一个包含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为null。

在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')

我错过了什么?

1 个答案:

答案 0 :(得分:0)

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

相关问题