使用 Spock 运行集成测试(例如 @IntegrationTest
)的最佳方式是什么?我想引导整个 Spring Boot 应用程序并执行一些 HTTP 调用来测试整个功能。
我可以用 JUnit 做到这一点(首先应用程序运行,然后执行测试):
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MyServer.class)
@WebAppConfiguration
@IntegrationTest
class MyTest {
RestTemplate template = new TestRestTemplate();
@Test
public void testDataRoutingWebSocketToHttp() {
def a = template.getForEntity("http://localhost:8080", String.class)
println a
}
}
但使用 Spock 时应用程序无法启动:
@SpringApplicationConfiguration(classes = MyServer.class)
@WebAppConfiguration
@IntegrationTest
class MyTestSpec extends Specification {
RestTemplate template = new TestRestTemplate();
def "Do my test"() {
setup:
def a = template.getForEntity("http://localhost:8080", String.class)
expect:
println a
}
}
当然,对于 Spock,我已经在我的 Gradle 构建文件中指定了正确的依赖项:
...
dependencies {
testCompile 'org.spockframework:spock-core:0.7-groovy-2.0'
testCompile 'org.spockframework:spock-spring:0.7-groovy-2.0'
}
...
我错过了什么吗?
最佳答案
问题是 Spock Spring 正在寻找 Spring 的 @ContextConfiguration
注释并且没有设法找到它。严格来说 MyTestSpec
is 用 @ContextConfiguration
注释,因为它是 @SpringApplicationConfiguration
上的元注释,但 Spock Spring 没有t 将元注释视为其搜索的一部分。有一个issue来解决这个限制。与此同时,您可以解决它。
@SpringApplicationConfiguration
所做的只是使用特定于引导的上下文加载器自定义 @ContextConfiguration
。这意味着您可以通过使用适当配置的 @ContextConfiguration
注释来实现相同的效果:
@ContextConfiguration(loader = SpringApplicationContextLoader.class, classes = MyServer.class)
@WebAppConfiguration
@IntegrationTest
class MyTestSpec extends Specification {
…
}
更新:只是为了确保它清楚(并且根据评论,它不是),要让它工作,你需要有 org.spockframework:spock-spring
在类路径上。
关于java - 使用 Spring Boot 和 Spock 进行集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24405727/