我已经使用从模型类初始化的空对象设置了Body
,ProviderServiceResponse
而不是使用匿名对象设置它,因为我想重用模型类并尽可能少地做。现在,我正在尝试生成一个协议/合同,指定只验证响应正文中属性的类型和存在,而不是其确切值。
我已经做了相当多的工作,但是当模型的属性为 String 类型时,Provider 端的验证似乎总是会失败(请参阅此问题的底部)。
我可以知道如何解决这个问题吗?
这是我到目前为止所拥有的:
模型类:用户
public class User
{
public long id {get; set;}
public string name { get; set; }
public string dob { get; set; }
}
消费者测试代码:
[Fact]
public void GetUser()
{
User user = new User();
_mockProviderService
.Given("There is a User")
.UponReceiving("A GET request to retrieve the User")
.With(new ProviderServiceRequest
{
Method = HttpVerb.Get,
Path = "/rest/user/1",
Headers = new Dictionary<string, object>
{
{ "Accept", "application/json" }
}
})
.WillRespondWith(new ProviderServiceResponse
{
Status = 200,
Headers = new Dictionary<string, object>
{
{ "Content-Type", "application/json" }
},
Body = Match.Type(user)
}); ;//NOTE: WillRespondWith call must come last as it will register the interaction
var consumer = new RestClient(_mockProviderServiceBaseUri);
//Act
var result = consumer.GetUser();
//Assert
Assert.IsType<User>(result.Result);
_mockProviderService.VerifyInteractions(); //NOTE: Verifies that interactions registered on the mock provider are called at least once
}
提供者测试代码:
[Fact]
public void TestProvider()
{
var config = new PactVerifierConfig
{
Outputters = new List<IOutput>
{
new XUnitOutput(_outputHelper)
},
Verbose = true,
CustomHeaders = new Dictionary<string, string>()
{
{ "Accept","application/json" }
}
};
IPactVerifier pactVerifier = new PactVerifier(config);
pactVerifier
.ServiceProvider(ProviderName, ProviderUri)
.HonoursPactWith(Consumer)
.PactUri($@"C:\Pacts\{Consumer}-{ProviderName}.json")
.Verify();
}
当我运行 Provider 测试时,我遇到了这个错误:
Failure/Error: expect(response_body).to match_term expected_response_body, diff_options, example
...
"user": {
- "name": NilClass,
- "dob": NilClass
+ "name": String,
+ "dob": String
}
Description of differences
--------------------------------------
* Expected nil but got a String ("Damien") at $.user.name
* Expected nil but got a String ("12/04/2021") at $.user.dob
解决方法
使用 AutoBogus 或类似工具在模型对象用于创建契约之前自动设置具有适当值的模型对象的属性。如果一切都失败了,那么这将是我要探索的解决方案。