为 Spring 启动应用程序编写 Spock 测试用例

Write Spock test cases for Spring boot application

我正在开发 spring 启动应用程序。我必须为它编写测试用例。我之前没有写过测试用例,所以有人建议使用 spock 框架。我探索了 spock,我认为它与 groovy 语言更相关。

我可以为我的 spring 应用程序编写 spock 测试用例吗?

如果是这样,你能建议我更好的 "how to use it with spring boot application" 文档吗?

是的,您可以为您的 spring 应用程序编写 spock 测试用例。

查看 official documentation 以获取使用 Spring Boot

进行 Spock 测试的示例

35.3.1 Using Spock to test Spring Boot applications

一个简单的 google 搜索揭示了 Using Spock to test Spring classes 的基本示例。

Spock relies heavily on the Spring's TestContext framework and does this via the @ContextConfiguration annotation. This allows the test specification class to load an application context from one or more locations.

Spring One g2x 有一个关于使用 Spock 测试 Java、Groovy、Spring 和 Web 应用程序的大型演示文稿。

Groovy 和 Java 可以自由混合在一起你可以使用任何你喜欢的基于 Java 的库,或者使用基于 Groovy 的库。

The Spring framework supports Groovy and - not surprisingly - Spring TestContext framework works well with Spock Spock specifications can be run from an IDE just like normal JUnit tests and, last but not least, implementing them is a great opportunity to learn the Groovy language.source

以下是帮助您使用 Spring 引导编写 spock 测试的步骤。

@ContextConfiguration(classes = StartApplication.class, loader =     SpringApplicationContextLoader.class)
@TestPropertySource(locations = "classpath:application-iTest.properties")
@WebAppConfiguration
@ComponentScan( "com.xyz")
@ActiveProfiles("iTest")
@IntegrationTest("server.port:0")
class TestAuditReport extends Specification{

   def Test1(){
    given :
    when:
    then:
    1==1
}

}
  • @ContextConfiguration(classes = StartApplication.class, loader = SpringApplicationContextLoader.class) // StartApplication.Java 是 main class which 运行 Spring 引导应用程序。
  • @TestPropertySource(位置= "classpath:application-iTest.properties") //
  • @WebAppConfiguration // 如果 Web 应用程序已在您的应用程序中配置。
  • @ComponentScan("com.xyx") // 要扫描的包名。
  • @ActiveProfiles("iTest") // 定义的配置文件名称即 iTest 因此文件名 "filePrefix-iTest.properties 将在 /test/java/resource 文件夹中查找
  • @IntegrationTest("server.port:0") // 它会 运行 任何端口号, 同样,仅当启用 @WebAppConfiguration 时才需要此注释。 class TestAuditReport 扩展规范