2

我正在尝试使用 pact jvm 对消费者驱动程序合同测试进行测试,并能够生成消费者端合同文件。在提供者端验证期间,如何提供公共 API 而不是 localhost 大多数示例仅使用 localhost 作为提供者,请提供任何帮助

@RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
@Provider("WeatherProvider") // Set up name of tested provider
@PactFolder("D:\Workspace\pactConsumer\pactConsumer_v2\pacts") // Point where to find pacts (See also section Pacts source in documentation)
@VerificationReports(value = {"markdown","json"}, reportDir = "D:\Workspace\pactConsumer\pactConsumer_v2\target")

public class ProviderVerifyer {
@State("Weather information is available for Chennai") // Method will be run before testing interactions that require "with-data" state
public void getWeather() {
System.out.println("Weather information is available for Chennai" );
}
@TestTarget // Annotation denotes Target that will be used for tests
public final Target target = new HttpTarget(8114); // Out-of-the-box implementation of Target (for more information take a look at Test Target section)

}
4

1 回答 1

0

这是可能的,但是——

在验证实时提供商之前,您需要仔细考虑 - 特别是您无法控制的提供商。任何改变服务器状态的东西(很可能)都被淘汰了。

但是,没有技术原因您不能运行某些提供者验证来检查您的消费者合同是否由当前部署的提供者履行。有host 和 port的构造函数:

public final Target target = new HttpTarget(host, port); 

需要注意的一些事项:

  • 编写测试以使其不依赖于数据非常重要。这意味着在您的消费者测试中使用匹配器来确保您正在验证从提供者返回的数据的形状(而不是验证从提供者返回的特定数据)。无论如何,这是编写消费者测试的好习惯。
  • 如果您的合同包含预期会更改服务器状态的请求,您可能会遇到问题(向实时提供者发出这些请求可能不合适,除非您能够以某种方式向沙盒环境发出请求)。
  • 根据您的合同规模和/或提供商获得的正常流量,对它运行您自己的自动化测试可能是不礼貌的。
  • 您将无法设置提供者状态。提供者状态用于避免合同测试之间存在相互依赖关系,因此如果您必须(例如)在执行其他任何操作之前发出登录请求,您可能会遇到麻烦 - 协议并非旨在让测试依赖于订单或包含不止一个请求。
  • 如果您的测试要交给在其他地方运行的实时部署提供商,您的测试可能会很脆弱——DNS、服务器正常运行时间、网络超时等的变化都可能导致您的测试意外失败。

更好的选择

最好的解决方案是让控制提供者的人使用(或包括)您的消费者生成的协议进行自己的验证。对于协议经纪人来说,这是一个很好的用例 - 但取决于您联系合适人的能力,这可能是一个挑战。

于 2018-01-10T00:03:00.990 回答