.Net下WireMock API测试:如何匹配动态RequestReference参数?
WireMock动态匹配RequestReference字段的解决方案
你之前用*作为通配符无效,是因为WithBodyAsJson默认是精确匹配,普通字符串里的*只会被当成普通字符处理。下面是几种可行的解决方法:
方法1:部分JSON匹配(最简便)
创建请求对象时,将RequestReference设为null(或不赋值),然后开启WireMock的部分匹配模式,这样它只会校验非null的字段,完全忽略RequestReference的具体值:
var response = new Response { CustomerId = CustomerReference, CustomerEmail = _customerInfo.EmailAddress, CustomerName = _customerInfo.FirstName + " " + _customerInfo.LastName, RequestDate = DateTime.UtcNow }; // 请求对象不设置RequestReference(或设为null) var request = new Request { CustomerEmail = customerEmail, CustomerId = customerId, CustomerName = customerName, RequestReference = null }; WireMockApiFake .Given(Request.Create() .WithPath("/api/customer") .UsingPost() // 开启部分匹配,只校验非null字段 .WithBodyAsJson(request, MatchBehaviour.AcceptOnMatch, JsonMatchMode.Partial)) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.OK) .WithBodyAsJson(response));
方法2:JsonPath表达式匹配
通过JsonPath精确指定需要匹配的字段,同时允许RequestReference为任意值:
var response = new Response { CustomerId = CustomerReference, CustomerEmail = _customerInfo.EmailAddress, CustomerName = _customerInfo.FirstName + " " + _customerInfo.LastName, RequestDate = DateTime.UtcNow }; WireMockApiFake .Given(Request.Create() .WithPath("/api/customer") .UsingPost() // 用JsonPath匹配固定字段,忽略RequestReference的具体值 .WithBody(x => x.JsonPath($"$.CustomerId == '{customerId}' && $.CustomerEmail == '{customerEmail}' && $.CustomerName == '{customerName}'"))) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.OK) .WithBodyAsJson(response));
方法3:自定义匹配器(灵活度最高)
如果需要更精细的规则(比如要求RequestReference非空),可以用WithBodyMatchers结合JsonMatcher逐个字段配置:
var response = new Response { CustomerId = CustomerReference, CustomerEmail = _customerInfo.EmailAddress, CustomerName = _customerInfo.FirstName + " " + _customerInfo.LastName, RequestDate = DateTime.UtcNow }; WireMockApiFake .Given(Request.Create() .WithPath("/api/customer") .UsingPost() .WithBodyMatchers( new JsonMatcher("$..CustomerId", Match.Equal(customerId)), new JsonMatcher("$..CustomerEmail", Match.Equal(customerEmail)), new JsonMatcher("$..CustomerName", Match.Equal(customerName)), // 匹配任意值(包括null),如果要限制非空可以用Match.NotEqual(null) new JsonMatcher("$..RequestReference", Match.Any()) )) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.OK) .WithBodyAsJson(response));
内容的提问来源于stack exchange,提问作者HurkanSeyhan
相关产品推荐
相关产品推荐

