在集成测试结束时停止空手道模拟服务器

Stopping Karate mock server at the end of Integration testing

我正在使用 Karate 对 Spring 启动应用程序进行集成测试。该应用程序使用另外两个服务(服务 A 和服务 B)。我已经为服务 A 和 B 编写了空手道模拟。我的集成测试被编写为两个不同的功能文件。其中一项功能使用 Mocks 测试服务 A 和 B。另一个功能使用 Mocks 测试服务 B,Spring Contract Stubs 测试服务 A。

只有模拟的特征

 Feature: Test Some feature

  Background:
    * configure headers = { Content-Type: 'application/json' }
    * url baseUrl

 #Start up the mocks
  Scenario: Start the Mocks
    * karate.start({ mock: '../mock/service/service-a.feature', port: 9000})
    * karate.start({ mock: '../mock/service/service-b.feature', port: 9001})

具有模拟和 Spring 合同存根的功能

 Feature: Test Some more features

  Background:
    * configure headers = { Content-Type: 'application/json' }
    * url baseUrl

 #Start up the mocks
  Scenario: Start the Mocks
    # Service A will use Spring Contract stubrunner. 
    * karate.start({ mock: '../mock/service/service-b.feature', port: 9001})

现在,当我们 运行 测试时,第二个失败说端口已被使用。我尝试在功能文件末尾使用 karate.stop(9000),首先是 运行ning,但它没有帮助。此外,我不确定此停止方法的行为。有什么解决这个问题的建议吗?为什么模拟服务在测试完成后仍然 运行ning?

据我所知,模拟应该在 JVM 退出时停止 - 所以我无法解释你的情况。所以也许你应该创建一种方法来复制和提交错误:https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

我个人建议从单元测试 Java 代码(通常是 JUnit class)开始模拟,这意味着您可以保留对模拟的引用然后调用 stop()在上面。即使在这里,通常也不是强制性的,因为模拟应该与 JVM 一起终止。在此处阅读文档:https://github.com/intuit/karate/tree/develop/karate-netty#embedding

然后,请注意最佳做法是动态提供端口,然后将其传递给测试或任何其他消费者。特别是在 CI-CD 管道中,这避免了端口正在使用或花费太多时间去分配的问题。

也许是您正在寻找的直接答案。当您调用 karate.start() 时,您会得到一个类型为 MockServer 的对象。所以你可以保留对它的引用并在需要时对其调用 stop()https://github.com/intuit/karate/tree/develop/karate-netty#within-a-karate-test

例如:

* def server1 = karate.start('mock1.feature')
* def port1 = server1.port
# do some tests
* server1.stop()