【问题标题】:Pact Testing PactProviderRule not detected未检测到 Pact 测试 PactProviderRule
【发布时间】:2020-04-22 17:12:36
【问题描述】:

我从 Pact 测试开始,我按照 Pact-JVM-Example 中的示例进行操作,然后我创建了自己的测试

生产者返回,来自用户的数据(一个非常简单的 JSON) { “身份证”:1, "firstName": "名字", “姓氏”:“最后一个” }

消费者测试是:

  public class HelloControllerTest {
  @Rule
  public PactProviderRuleMk2 provider = new PactProviderRuleMk2("DemoService", "localhost", 8112, this);

  @Pact(consumer = "DemoClient")
  public RequestResponsePact createFragment(PactDslWithProvider builder) {
    Map<String, String> headers = new HashMap();
    headers.put("Content-Type", "application/json");

    DslPart userResult = new PactDslJsonBody()
        .integerType("id",1)
        .stringType("fistName","name")
        .stringType("lastName","last")
        .asBody();

    return builder
        .given("There is a user with Id 1")
        .uponReceiving("A request for user 1")
        .path("/user/1")
        .method("GET")
        .willRespondWith()
        .status(200)
        .headers(headers)
        .body(userResult).toPact();
  }

  @Test
  @PactVerification()
  public void doTest() {
    HelloController helloController = new HelloController(provider.getPort());
  }
}

消费者类看起来像:

public class HelloController {

  int port = 8200;

   HelloController(){
    // Will use default port.
    System.out.println("Default port "+ port);
  }

  HelloController(int port){
    this.port = port;
    System.out.println("Custom port "+ port);
  }

  public boolean getUser(){

    try {
    String url=String.format("http://localhost:%d/user/%d", port, 1);
    System.out.println("using url: " + url);
    HttpResponse r = Request.Get(url).execute().returnResponse();
    String json = EntityUtils.toString(r.getEntity());
    System.out.println("json = " + json);
    return true;
    }
    catch (Exception e) {
      System.out.println("Unable to get user");
      return false;
    }

  }

}

我注意到当我运行@Test 时:

 @Test
  @PactVerification()
  public void doTest() {
    HelloController helloController = new HelloController(provider.getPort());
  }

我收到 NullPointerException。

测试没有从提供者获取模拟数据,在@Rule 中声明

@Rule
  public PactProviderRuleMk2 provider = new PactProviderRuleMk2("DemoService", "localhost", 8112, this);

我不知道缺少什么,为什么没有检测到 Mock 提供程序?

任何建议, 谢谢

【问题讨论】:

    标签: java unit-testing junit microservices pact


    【解决方案1】:

    您必须在测试方法上注明您的 Pact 片段。

    @PactVerification(fragment = "createFragment")
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 2020-12-23
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多