【问题标题】:How to start with PACT contract testing in java for a newbie如何在 Java 中为新手开始 PACT 合同测试
【发布时间】:2020-02-07 17:49:30
【问题描述】:

我必须使用 pact 对合同测试进行 POC,但我找不到任何对新手有帮助的东西。有人可以帮我提供工作代码,如何安装,执行我将不胜感激。

【问题讨论】:

标签: pact contract


【解决方案1】:

我试着在下面解释。

消费者:消费者创建的合约。

提供者:由提供者测试的合约。

Pack Broker:在您定义的位置(如目标/契约)下创建合同后,您必须将合同发布到消费者和提供者将看到的公共平台。

消费者方 - 为提供者创建合同

public class CreateContractForProvider {
@Rule //Provider, HostInterface and Port defined with @Rule annotation (Used PactProviderRuleMk2)

public PactProviderRuleMk2 pactProviderRuleMk2 = new PactProviderRuleMk2(
        // Provider Application Name
        "ProviderName",

        //Mock Server
        "localhost",
        8112,

        this);

@Pact(consumer = "ConsumerName") // Consumer Application Name (Our application) - Consumer defined with @Pact annotation(

public RequestResponsePact createPact(PactDslWithProvider builder) {

    Map<String, String> headers = new HashMap();
    headers.put("Content-Type", "application/json"); //Defined headers


    //Defined responses with PactDslJsonBody()
    DslPart expectedResultBodyWhenGetPayments = new PactDslJsonBody()
            .integerType("id",308545)
            .integerType("contractNo",854452)
            .numberType("amount",3312.5)
            .stringType("status","UNPAID")
            .asBody();


    return builder
            .uponReceiving("A request for all payments")
            .path("/payments")
            .method("GET")
            .willRespondWith()
            .status(200)
            .headers(headers)
            .body(expectedResultBodyWhenGetPayments).toPact(); //Response bodyies and headers used in return builder
  //  We can define more than one endpoint with .uponReceiving or .given



 //Then we have to test beacuse contracts are created test stage. 
 //When we say test with  @PactVerification, the server we described above stands up(localhost:8112). İf we get localhost:8112/(definedpathlike/payments) its return expectedResultBodyWhenGetPayments.If the test is successful, the contracts is create.
 @Test
 @PactVerification()
public void pactVerification() {    

    int contractNo=((Integer) new   ContractTestUtil(pactProviderRuleMk2.getPort()).getContractResponse("/payments","contractNo")).intValue();
    assertTrue(contractNo == 854452);
}}

测试工具

public class ContractTestUtil {

int port=8111;

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

public  Object getContractResponse(String path,String object) {
    try {
        System.setProperty("pact.rootDir", "./target/pacts");
        System.setProperty("pact.rootDir", "./target/pacts");

        String url=String.format("Http://localhost:%d"+path, port);
        System.out.println("using url: "+url);
        HttpResponse httpResponse = Request.Get(url).execute().returnResponse();
        String json = EntityUtils.toString(httpResponse.getEntity());
        System.out.println("json="+json);
        JSONObject jsonObject = new JSONObject(json);
        return jsonObject.get(object);
    }
    catch (Exception e) {
        System.out.println("Unable to get object="+e);
        return null;
    }
}}

定义 Pact Broker

必须在 pom 中发布之前定义 PactBrokerUr。

            <plugin>
            <!-- mvn pact:publish  -->
            <groupId>au.com.dius</groupId>
            <artifactId>pact-jvm-provider-maven_2.11</artifactId>
            <version>3.5.10</version>
            <configuration>
                <pactDirectory>./target/pacts</pactDirectory> <!-- Defaults to ${project.build.directory}/pacts -->
                <pactBrokerUrl>http://yourmachine:8113</pactBrokerUrl>
                <projectVersion>1.1</projectVersion> <!-- Defaults to ${project.version} -->
                <trimSnapshot>true</trimSnapshot> <!-- Defaults to false -->
            </configuration>
        </plugin>

现在,我们可以使用 pact:puplish 命令发布。

Provider Side - 调用消费者创建的合约

在这个阶段,您可以使用故障安全插件进行测试。因为它的集成测试。

@RunWith(PactRunner.class) // Say JUnit to run tests with custom Runner
@Provider("ProviderName")
@Consumer("ConsumerName")// Set up name of tested provider// Provider Application Name
@PactBroker(port = "8113", host = "yourmachine")
public class VerifyContractsWhichCreatedForProviderIT {

private static ConfigurableWebApplicationContext configurableWebApplicationContext;

@BeforeClass
public static void start() {
    configurableWebApplicationContext = (ConfigurableWebApplicationContext)
      SpringApplication.run(Application.class);
}

@TestTarget // Annotation denotes Target that will be used for tests
public final Target target = new HttpTarget(8080); //Test Target
}

最后,您可以使用clean test pact:publish verify 命令创建对比度并验证为您创建的对比度。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-12-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 2019-02-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-30
相关资源
最近更新 更多