Skip to content

Commit 336cb7c

Browse files
committed
Fix Request.Create().WithBodyAsJson(...)
1 parent 13f87a1 commit 336cb7c

File tree

4 files changed

+31
-102
lines changed

4 files changed

+31
-102
lines changed

examples/WireMock.Net.Console.Net452.Classic/MainApp.cs

+22-41
Original file line numberDiff line numberDiff line change
@@ -97,34 +97,30 @@ type Student {
9797

9898
private static void RunOnLocal()
9999
{
100-
var localIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(a => a.AddressFamily == AddressFamily.InterNetwork);
101-
102-
//try
103-
//{
104-
// var server = WireMockServer.Start(new WireMockServerSettings
105-
// {
106-
// Urls = new[] { $"http://{localIP}:9091" },
107-
// StartAdminInterface = true
108-
// });
109-
// System.Console.WriteLine($"1: {string.Join(", ", server.Urls)}");
110-
111-
// System.Console.WriteLine("Press any key to stop...");
112-
// System.Console.ReadKey();
113-
// server.Stop();
114-
//}
115-
//catch (Exception e)
116-
//{
117-
// System.Console.WriteLine(e);
118-
//}
119-
120100
try
121101
{
122102
var server = WireMockServer.Start(new WireMockServerSettings
123103
{
124104
Port = 9091,
125-
StartAdminInterface = true
105+
StartAdminInterface = true,
106+
Logger = new WireMockConsoleLogger()
126107
});
127-
System.Console.WriteLine($"2: {string.Join(", ", server.Urls)}");
108+
System.Console.WriteLine(string.Join(", ", server.Urls));
109+
110+
var requestJson = new { PricingContext = new { Market = "USA" } };
111+
var responseJson = new { Market = "{{JsonPath.SelectToken request.body \"$.PricingContext.Market\"}}" };
112+
server
113+
.Given(Request.Create()
114+
//.WithBody(new JsonMatcher(requestJson))
115+
.WithBodyAsJson(requestJson)
116+
.WithPath("/pricing")
117+
.UsingPost()
118+
)
119+
.RespondWith(Response.Create()
120+
.WithHeader("Content-Type", "application/json")
121+
.WithBodyAsJson(responseJson)
122+
.WithTransformer(true)
123+
);
128124

129125
System.Console.WriteLine("Press any key to stop...");
130126
System.Console.ReadKey();
@@ -134,24 +130,6 @@ private static void RunOnLocal()
134130
{
135131
System.Console.WriteLine(e);
136132
}
137-
138-
//try
139-
//{
140-
// var server = WireMockServer.Start(new WireMockServerSettings
141-
// {
142-
// Urls = new[] { "http://*:9091" },
143-
// StartAdminInterface = true
144-
// });
145-
// System.Console.WriteLine($"3: {string.Join(", ", server.Urls)}");
146-
147-
// System.Console.WriteLine("Press any key to stop...");
148-
// System.Console.ReadKey();
149-
// server.Stop();
150-
//}
151-
//catch (Exception e)
152-
//{
153-
// System.Console.WriteLine(e);
154-
//}
155133
}
156134

157135
public static void Run()
@@ -251,7 +229,10 @@ public static void Run()
251229
server.SetBasicAuthentication("a", "b");
252230
//server.SetAzureADAuthentication("6c2a4722-f3b9-4970-b8fc-fac41e29stef", "8587fde1-7824-42c7-8592-faf92b04stef");
253231

254-
// server.AllowPartialMapping();
232+
233+
//var http = new HttpClient();
234+
//var response = await http.GetAsync($"{_wireMockServer.Url}/pricing");
235+
//var value = await response.Content.ReadAsStringAsync();
255236

256237
#if PROTOBUF
257238
var protoBufJsonMatcher = new JsonPartialWildcardMatcher(new { name = "*" });

src/WireMock.Net/RequestBuilders/IBodyRequestBuilder.cs

+1-11
Original file line numberDiff line numberDiff line change
@@ -51,23 +51,13 @@ public interface IBodyRequestBuilder : IProtoBufRequestBuilder
5151
IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
5252

5353
/// <summary>
54-
/// WithBody : Body as a string response based on a object (which will be converted to a JSON string using NewtonSoft.Json).
54+
/// WithBodyAsJson: A <see cref="JsonMatcher"/> will be used to match this object.
5555
/// </summary>
5656
/// <param name="body">The body.</param>
5757
/// <param name="matchBehaviour">The match behaviour [default is AcceptOnMatch].</param>
5858
/// <returns>A <see cref="IRequestBuilder"/>.</returns>
5959
IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
6060

61-
/// <summary>
62-
/// WithBody : Body as a string response based on a object (which will be converted to a JSON string using the <see cref="IJsonConverter"/>).
63-
/// </summary>
64-
/// <param name="body">The body.</param>
65-
/// <param name="converter">The JsonConverter.</param>
66-
/// <param name="options">The <see cref="JsonConverterOptions"/> [optional].</param>
67-
/// <param name="matchBehaviour">The match behaviour [default is AcceptOnMatch].</param>
68-
/// <returns>A <see cref="IRequestBuilder"/>.</returns>
69-
IRequestBuilder WithBodyAsJson(object body, IJsonConverter converter, JsonConverterOptions? options = null, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch);
70-
7161
/// <summary>
7262
/// WithBody: func (string)
7363
/// </summary>

src/WireMock.Net/RequestBuilders/Request.WithBody.cs

+1-15
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,6 @@
22
// For more details see 'mock4net/LICENSE.txt' and 'mock4net/readme.md' in this project root.
33
using System;
44
using System.Collections.Generic;
5-
using JsonConverter.Abstractions;
6-
using Newtonsoft.Json;
75
using Stef.Validation;
86
using WireMock.Matchers;
97
using WireMock.Matchers.Request;
@@ -37,19 +35,7 @@ public IRequestBuilder WithBody(object body, MatchBehaviour matchBehaviour = Mat
3735
/// <inheritdoc />
3836
public IRequestBuilder WithBodyAsJson(object body, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
3937
{
40-
var bodyAsJsonString = JsonConvert.SerializeObject(body);
41-
_requestMatchers.Add(new RequestMessageBodyMatcher(matchBehaviour, bodyAsJsonString));
42-
return this;
43-
}
44-
45-
/// <inheritdoc />
46-
public IRequestBuilder WithBodyAsJson(object body, IJsonConverter converter, JsonConverterOptions? options = null, MatchBehaviour matchBehaviour = MatchBehaviour.AcceptOnMatch)
47-
{
48-
Guard.NotNull(converter);
49-
50-
var bodyAsJsonString = converter.Serialize(body, options);
51-
_requestMatchers.Add(new RequestMessageBodyMatcher(matchBehaviour, bodyAsJsonString));
52-
return this;
38+
return WithBody(new IMatcher[] { new JsonMatcher(matchBehaviour, body) });
5339
}
5440

5541
/// <inheritdoc />

test/WireMock.Net.Tests/RequestBuilders/RequestBuilderWithBodyTests.cs

+7-35
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
using System.Collections.Generic;
44
using System.Linq;
55
using System.Text;
6-
using JsonConverter.Abstractions;
7-
using Moq;
86
using Newtonsoft.Json;
97
using NFluent;
108
using WireMock.Matchers;
@@ -293,7 +291,7 @@ public void Request_WithBodyJson_PathMatcher_false()
293291
}
294292

295293
[Fact]
296-
public void Request_WithBodyAsJson_Object_JsonPathMatcher_true()
294+
public void Request_WithBody_Object_JsonPathMatcher_true()
297295
{
298296
// Arrange
299297
var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..things[?(@.name == 'RequiredThing')]"));
@@ -316,7 +314,7 @@ public void Request_WithBodyAsJson_Object_JsonPathMatcher_true()
316314
}
317315

318316
[Fact]
319-
public void Request_WithBodyAsJson_Array_JsonPathMatcher_1()
317+
public void Request_WithBody_Array_JsonPathMatcher_1()
320318
{
321319
// Arrange
322320
var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..books[?(@.price < 10)]"));
@@ -339,7 +337,7 @@ public void Request_WithBodyAsJson_Array_JsonPathMatcher_1()
339337
}
340338

341339
[Fact]
342-
public void Request_WithBodyAsJson_Array_JsonPathMatcher_2()
340+
public void Request_WithBody_Array_JsonPathMatcher_2()
343341
{
344342
// Arrange
345343
var spec = Request.Create().UsingAnyMethod().WithBody(new JsonPathMatcher("$..[?(@.Id == 1)]"));
@@ -363,7 +361,7 @@ public void Request_WithBodyAsJson_Array_JsonPathMatcher_2()
363361
}
364362

365363
[Fact]
366-
public void Request_WithBodyAsObject_ExactObjectMatcher_true()
364+
public void Request_WithBody_ExactObjectMatcher_true()
367365
{
368366
// Assign
369367
object body = DateTime.MinValue;
@@ -384,7 +382,7 @@ public void Request_WithBodyAsObject_ExactObjectMatcher_true()
384382
}
385383

386384
[Fact]
387-
public void Request_WithBodyAsJson_UsingObject()
385+
public void Request_WithBodyAsJson_UsingObject_UsesJsonMatcher()
388386
{
389387
// Assign
390388
object body = new
@@ -395,34 +393,8 @@ public void Request_WithBodyAsJson_UsingObject()
395393

396394
var bodyData = new BodyData
397395
{
398-
BodyAsString = JsonConvert.SerializeObject(body),
399-
DetectedBodyType = BodyType.String
400-
};
401-
402-
// Act
403-
var request = new RequestMessage(new UrlDetails("http://localhost/foo"), "POST", ClientIp, bodyData);
404-
405-
// Assert
406-
var requestMatchResult = new RequestMatchResult();
407-
Check.That(requestBuilder.GetMatchingScore(request, requestMatchResult)).IsEqualTo(1.0);
408-
}
409-
410-
[Fact]
411-
public void Request_WithBodyAsJson_WithIJsonConverter_UsingObject()
412-
{
413-
// Assign
414-
var jsonConverterMock = new Mock<IJsonConverter>();
415-
jsonConverterMock.Setup(j => j.Serialize(It.IsAny<object>(), It.IsAny<JsonConverterOptions>())).Returns("test");
416-
object body = new
417-
{
418-
Any = "key"
419-
};
420-
var requestBuilder = Request.Create().UsingAnyMethod().WithBodyAsJson(body, jsonConverterMock.Object);
421-
422-
var bodyData = new BodyData
423-
{
424-
BodyAsString = "test",
425-
DetectedBodyType = BodyType.String
396+
BodyAsJson = body,
397+
DetectedBodyType = BodyType.Json
426398
};
427399

428400
// Act

0 commit comments

Comments
 (0)