为Spring Boot应用编写Spock测试案例

6

我正在开发一个Spring Boot应用程序。我需要为它编写测试用例。我以前没有写过测试用例,所以有人建议我使用Spock框架。我探索了一下Spock,我认为它更与Groovy语言相关。

那么,我能否为我的Spring应用程序编写Spock测试用例呢?

如果可以的话,你能否向我推荐一个更好的“如何在Spring Boot应用程序中使用Spock框架”的文档?


1
是的,你可以编写这样的测试。但是这个问题可能会被关闭,因为它不在主题范围内。你需要提出更详细的问题。 - Opal
2个回答

9

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

查看官方文档,了解使用Spring Boot进行Spock测试的示例

35.3.1 使用Spock测试Spring Boot应用程序

简单的谷歌搜索就能找到一个基本的使用Spock测试Spring类的示例。

Spock在很大程度上依赖于Spring的TestContext框架,并通过@ContextConfiguration注释来实现这一点。这允许测试规范类从一个或多个位置加载应用程序上下文。

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

Groovy和Java可以自由混合使用,您可以使用任何基于Java的库,也可以使用基于Groovy的库。

Spring框架支持Groovy语言,而Spring TestContext框架与Spock非常兼容。可以像运行普通JUnit测试一样从IDE中运行Spock规范,实现它们是学习Groovy语言的绝佳机会。source

感谢您的详细解释,我在很多地方看到它用于Groovy语法,例如: def "adder-test"() { given: "a new Adder class is created" def adder = new Adder(); expect: "Adding two numbers to return the sum" adder.add(3, 4) == 7 } 但我不想使用这种方式,我能否不使用def等来实现呢? - Prabjot Singh
如果你想使用Spock,你将会使用Groovy,但这没关系,因为Spring框架支持Groovy,并且Groovy可以自由地与Java混合使用。这是你知识库中不错的补充。 - Laurentiu L.

2
以下是使用Spring Boot编写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 是运行 Spring Boot 应用程序的主类。
  • @TestPropertySource(locations = "classpath:application-iTest.properties") //
  • @WebAppConfiguration // 如果你的应用程序配置了 Web 应用程序,则需要使用此注释。
  • @ComponentScan("com.xyx") // 要扫描的包名。
  • @ActiveProfiles("iTest") // 定义了配置文件前缀为 "filePrefix-iTest.properties" 的配置文件将在 /test/java/resource 文件夹中查找,因此使用了 iTest 作为配置文件的 profile 名称。
  • @IntegrationTest("server.port:0") // 它会运行任何端口号,当 @WebAppConfiguration 启用时才需要使用此注释。class TestAuditReport extends Specification

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接