c# - 契约.net : Get the request that was sent to the mock service

标签 c# .net mocking pact

我正在为一项服务在开发人员解决方案中编写测试,并且正在使用 pact mock 服务模拟其他第三方服务。 我需要验证发送到该模拟服务的请求。所以我需要获取实际发送的有效载荷。 (实际存储到以“Received request”开头的日志文件中的那个)

非常感谢您的帮助

最佳答案

Pact 会为您验证消费者请求。看看this example .

对于消费者来说,测试过程是:

  1. 描述预期的请求
  2. 描述预期的响应
  3. 调用消费者用来生成响应的代码。 (此步骤实际上会访问模拟服务器 - 如果它收到预期的请求,它会返回预期的响应)。
  4. 验证消费者代码是否返回了预期的数据
  5. 验证模拟服务器收到了正确的请求

我将第 5 步加粗,因为这是检查请求的步骤。

(另请注意,如果请求不正确,第 3 步不会生成正确的响应,因此第 4 步几乎总是会失败)

这是 the example I linked above 的分割进入我刚刚列出的消费者测试步骤:

描述预期的请求

_mockProviderService
  .Given("There is a something with id 'tester'")
  .UponReceiving("A GET request to retrieve the something")
  .With(new ProviderServiceRequest
  {
    Method = HttpVerb.Get,
    Path = "/somethings/tester",
    Headers = new Dictionary<string, object>
    {
      { "Accept", "application/json" }
    }
  })

描述预期的响应

 .WillRespondWith(new ProviderServiceResponse
  {
    Status = 200,
    Headers = new Dictionary<string, object>
    {
      { "Content-Type", "application/json; charset=utf-8" }
    },
    Body = new //NOTE: Note the case sensitivity here, the body will be serialised as per the casing defined
    {
      id = "tester",
      firstName = "Totally",
      lastName = "Awesome"
    }
  }); //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 once and only once

^ 这是验证发送的请求是否正确所需的步骤。

关于c# - 契约.net : Get the request that was sent to the mock service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42366218/

相关文章:

c# - 如何强制派生类实现静态属性或字段?

c# - 使用 ApplicationSettingsBase 存储通用 List<CustomObject>

c# - ASP.NET MVC 3 服务器端验证因 ViewModel 中的下拉列表集合而失败

c# - 我怎样才能避免出现异常?关闭我的项目时无法访问已处置的对象

php - Symfony 服务中的模拟邮件程序

c++ - 声明所有虚拟方法以使用 gtest 进行模拟?

c# - 使用 C# 以编程方式最小化应用程序

c# - 基于 ViewModel 状态显示 UI 错误消息的最佳实践

c# - 字符串长度的 linq 函数 OrderByDescending 和 OrderBy 在内部如何工作?它比用循环做更快吗?

Perl 单元测试模拟