我正在为一项服务在开发人员解决方案中编写测试,并且正在使用 pact mock 服务模拟其他第三方服务。 我需要验证发送到该模拟服务的请求。所以我需要获取实际发送的有效载荷。 (实际存储到以“Received request”开头的日志文件中的那个)
非常感谢您的帮助
最佳答案
Pact 会为您验证消费者请求。看看this example .
对于消费者来说,测试过程是:
- 描述预期的请求
- 描述预期的响应
- 调用消费者用来生成响应的代码。 (此步骤实际上会访问模拟服务器 - 如果它收到预期的请求,它会返回预期的响应)。
- 验证消费者代码是否返回了预期的数据
- 验证模拟服务器收到了正确的请求
我将第 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/