微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将 Pact 合约测试从 JavaScript 重写为 C#

如何解决将 Pact 合约测试从 JavaScript 重写为 C#

如果这个问题违反了规则,我们深表歉意。

我有这个 js 课:

src/get.js

const { get } = require('axios')

module.exports = function () {
    return get(`http://localhost:1234/token/1234`)
}

还有这个测试:

consumer.pact.js

const path = require("path")
const chai = require("chai")
const { Pact,Matchers } = require("@pact-foundation/pact")
const chaiAsPromised = require("chai-as-promised")
const expect = chai.expect
chai.use(chaiAsPromised)
const { string } = Matchers
const get = require('../src/get')

describe('Consumer Test',() => {
    const provider = new Pact({
        consumer: "React",provider: "token",port: 1234,log: path.resolve(process.cwd(),'logs','pact.log'),dir: path.resolve(process.cwd(),'pacts'),logLevel: "INFO"
    });

    before(() => provider.setup()
    .then(() => provider.addInteraction({
        state: "user token",uponReceiving: "GET user token",withRequest: {
            method: "GET",path: "/token/1234",headers: { Accept: "application/json,text/plain,*/*" }
        },willRespondWith: {
            headers: { "Content-Type": "application/json" },status: 200,body: { "token": string("bearer") }
        }
    })))

    it('OK response',() => {
        get()
        .then((response) => {
            expect(response.statusText).to.be.equal('OK')
        })
    })

    after(() => provider.finalize())
})

我正在尝试使用 js 代码和示例 here 在 C# 中编写等效代码。除了 GET 之外,我已经完成了所有工作,不可否认,到目前为止我所做的可能还有很长的路要走。这是我到目前为止所拥有的:

ConsumerTest.cs

//using NUnit.Framework;
using System.Collections.Generic;
using PactNet;
using PactNet.Mocks.MockHttpService;
using PactNet.Mocks.MockHttpService.Models;
using Xunit;

namespace PactTests.PactTests
{
  public class ConsumerTest : IClassFixture<ConsumerPact>
  {
    private IMockProviderService _mockProviderService;
    private string _mockProviderServiceBaseUri;

    public ConsumerTest(ConsumerPact data)
    {
      _mockProviderService = data.MockProviderService;
      _mockProviderService.ClearInteractions(); //NOTE: Clears any prevIoUsly registered interactions before the test is run
      _mockProviderServiceBaseUri = data.MockProviderServiceBaseUri;
    }

    [Fact]
    public void OKResponse()
    {
      //Arrange
      _mockProviderService
        .Given("user token")
        .UponReceiving("GET user token")
        .With(new ProviderServiceRequest
        {
          Method = HttpVerb.Get,Path = "/token/1234",Headers = new Dictionary<string,object>
          {
            { "Accept","application/json,*/*" }
          }
        })
        .WillRespondWith(new ProviderServiceResponse
        {
          Status = 200,object>
          {
            { "Content-Type","application/json" }
          },Body = new //NOTE: Note the case sensitivity here,the body will be serialised as per the casing defined
          {
            token = "bearer"
          }
        }); //NOTE: WillRespondWith call must come last as it will register the interaction

        var consumer = new Somethingapiclient(_mockProviderServiceBaseUri);

      //Act
      var result = consumer.GetSomething("tester");

      //Assert
      Assert.Equal("tester",result.id);

      _mockProviderService.VerifyInteractions(); //NOTE: Verifies that interactions registered on the mock provider are called at least once
    }
  }
}

ConsumerPact.cs

using PactNet;
using PactNet.Mocks.MockHttpService;
using System;

namespace PactTests.PactTests
{
  public class ConsumerPact : Idisposable
  {
    public IPactBuilder PactBuilder { get; private set; }
    public IMockProviderService MockProviderService { get; private set; }

    public int MockServerPort { get { return 1234; } }

    public string MockProviderServiceBaseUri { get { return String.Format("http://localhost:{0}",MockServerPort); } }

    public ConsumerPact()
    {
      // Pact configuration
      var pactConfig = new PactConfig
      {
        SpecificationVersion = "2.0.17",PactDir = @"Users/paulcarron/git/pact/pacts",LogDir = @"Users/paulcarron/git/pact/logs"
      };

      PactBuilder = new PactBuilder(pactConfig);

      PactBuilder
        .ServiceConsumer("React")
        .HasPactWith("token");

      MockProviderService = PactBuilder.MockService(MockServerPort);

    }

    public void dispose()
    {
      PactBuilder.Build();
    }
  }
}

我该怎么做GET

解决方法

做什么

var consumer = new SomethingApiClient(_mockProviderServiceBaseUri);
...
var result = consumer.GetSomething("tester");

做什么?

那应该是执行 HTTP GET 的 API 客户端代码。任何 HTTP 客户端库都可以完成这项工作,但重要的是,它应该是您创建的用于与提供者通信的 API 客户端。

请参阅 https://github.com/pact-foundation/pact-workshop-dotnet-core-v1/blob/master/CompletedSolution/Consumer/src/ConsumerApiClient.cs 以获取可以从您的 JS 代码替换 axios 客户端的示例 API 客户端。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。