Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d5fa385

Browse files
authored
Fix FluentAssertions (actual body is not displayed in error message) (wiremock#1085)
* Fix FluentAssertions (actual body is not displayed in error message) * . * . * raw
1 parent 27a6739 commit d5fa385

File tree

3 files changed

+149
-36
lines changed

3 files changed

+149
-36
lines changed

src/WireMock.Net.FluentAssertions/Assertions/WireMockAssertions.WithBody.cs

Lines changed: 28 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,20 @@
11
#pragma warning disable CS1591
22
using System;
33
using System.Collections.Generic;
4+
using AnyOfTypes;
5+
using Newtonsoft.Json;
6+
using Newtonsoft.Json.Linq;
7+
using WireMock.Extensions;
48
using WireMock.Matchers;
9+
using WireMock.Models;
510

611
// ReSharper disable once CheckNamespace
712
namespace WireMock.FluentAssertions;
813

914
public partial class WireMockAssertions
1015
{
1116
private const string MessageFormatNoCalls = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but no calls were made.";
12-
private const string MessageFormat = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but didn't find it among the body {1}.";
17+
private const string MessageFormat = "Expected {context:wiremockserver} to have been called using body {0}{reason}, but didn't find it among the body/bodies {1}.";
1318

1419
[CustomAssertion]
1520
public AndConstraint<WireMockAssertions> WithBody(string body, string because = "", params object[] becauseArgs)
@@ -56,7 +61,7 @@ public AndConstraint<WireMockAssertions> WithBodyAsBytes(ExactObjectMatcher matc
5661
{
5762
var (filter, condition) = BuildFilterAndCondition(r => r.BodyAsBytes, matcher);
5863

59-
return ExecuteAssertionWithBodyAsBytesExactObjectMatcher(matcher, because, becauseArgs, condition, filter, r => r.BodyAsBytes);
64+
return ExecuteAssertionWithBodyAsIObjectMatcher(matcher, because, becauseArgs, condition, filter, r => r.BodyAsBytes);
6065
}
6166

6267
private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyStringMatcher(
@@ -74,14 +79,14 @@ private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyStringMatcher(
7479
.ForCondition(requests => CallsCount == 0 || requests.Any())
7580
.FailWith(
7681
MessageFormatNoCalls,
77-
matcher.GetPatterns()
82+
FormatBody(matcher.GetPatterns())
7883
)
7984
.Then
8085
.ForCondition(condition)
8186
.FailWith(
8287
MessageFormat,
83-
_ => matcher.GetPatterns(),
84-
requests => requests.Select(expression)
88+
_ => FormatBody(matcher.GetPatterns()),
89+
requests => FormatBodies(requests.Select(expression))
8590
);
8691

8792
FilterRequestMessages(filter);
@@ -104,48 +109,37 @@ private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyAsIObjectMatch
104109
.ForCondition(requests => CallsCount == 0 || requests.Any())
105110
.FailWith(
106111
MessageFormatNoCalls,
107-
matcher.Value
112+
FormatBody(matcher.Value)
108113
)
109114
.Then
110115
.ForCondition(condition)
111116
.FailWith(
112117
MessageFormat,
113-
_ => matcher.Value,
114-
requests => requests.Select(expression)
118+
_ => FormatBody(matcher.Value),
119+
requests => FormatBodies(requests.Select(expression))
115120
);
116121

117122
FilterRequestMessages(filter);
118123

119124
return new AndConstraint<WireMockAssertions>(this);
120125
}
121126

122-
private AndConstraint<WireMockAssertions> ExecuteAssertionWithBodyAsBytesExactObjectMatcher(
123-
ExactObjectMatcher matcher,
124-
string because,
125-
object[] becauseArgs,
126-
Func<IReadOnlyList<IRequestMessage>, bool> condition,
127-
Func<IReadOnlyList<IRequestMessage>, IReadOnlyList<IRequestMessage>> filter,
128-
Func<IRequestMessage, object?> expression
129-
)
127+
private static string? FormatBody(object? body)
130128
{
131-
Execute.Assertion
132-
.BecauseOf(because, becauseArgs)
133-
.Given(() => RequestMessages)
134-
.ForCondition(requests => CallsCount == 0 || requests.Any())
135-
.FailWith(
136-
MessageFormatNoCalls,
137-
matcher.Value
138-
)
139-
.Then
140-
.ForCondition(condition)
141-
.FailWith(
142-
MessageFormat,
143-
_ => matcher.Value,
144-
requests => requests.Select(expression)
145-
);
146-
147-
FilterRequestMessages(filter);
129+
return body switch
130+
{
131+
null => null,
132+
string str => str,
133+
AnyOf<string, StringPattern>[] stringPatterns => FormatBodies(stringPatterns.Select(p => p.GetPattern())),
134+
byte[] bytes => $"byte[{bytes.Length}] {{...}}",
135+
JToken jToken => jToken.ToString(Formatting.None),
136+
_ => JToken.FromObject(body).ToString(Formatting.None)
137+
};
138+
}
148139

149-
return new AndConstraint<WireMockAssertions>(this);
140+
private static string? FormatBodies(IEnumerable<object?> bodies)
141+
{
142+
var valueAsArray = bodies as object[] ?? bodies.ToArray();
143+
return valueAsArray.Length == 1 ? FormatBody(valueAsArray.First()) : $"[ {string.Join(", ", valueAsArray.Select(FormatBody))} ]";
150144
}
151145
}

src/WireMock.Net/Extensions/AnyOfExtensions.cs

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,18 +5,36 @@
55

66
namespace WireMock.Extensions;
77

8-
internal static class AnyOfExtensions
8+
/// <summary>
9+
/// Some extensions for AnyOf.
10+
/// </summary>
11+
public static class AnyOfExtensions
912
{
13+
/// <summary>
14+
/// Gets the pattern.
15+
/// </summary>
16+
/// <param name="value">AnyOf type</param>
17+
/// <returns>string value</returns>
1018
public static string GetPattern(this AnyOf<string, StringPattern> value)
1119
{
1220
return value.IsFirst ? value.First : value.Second.Pattern;
1321
}
1422

23+
/// <summary>
24+
/// Converts a string-patterns to AnyOf patterns.
25+
/// </summary>
26+
/// <param name="patterns">The string patterns</param>
27+
/// <returns>The AnyOf patterns</returns>
1528
public static AnyOf<string, StringPattern>[] ToAnyOfPatterns(this IEnumerable<string> patterns)
1629
{
1730
return patterns.Select(p => p.ToAnyOfPattern()).ToArray();
1831
}
1932

33+
/// <summary>
34+
/// Converts a string-pattern to AnyOf pattern.
35+
/// </summary>
36+
/// <param name="pattern">The string pattern</param>
37+
/// <returns>The AnyOf pattern</returns>
2038
public static AnyOf<string, StringPattern> ToAnyOfPattern(this string pattern)
2139
{
2240
return new AnyOf<string, StringPattern>(pattern);

test/WireMock.Net.Tests/FluentAssertions/WireMockAssertionsTests.cs

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,11 @@ public async Task HaveReceived1Call_WithBodyAsJson()
702702
// Act
703703
var httpClient = new HttpClient();
704704

705-
await httpClient.PostAsync($"{server.Url}/a", new StringContent(@"{ ""x"": ""y"" }"));
705+
var requestBody = new
706+
{
707+
x = "y"
708+
};
709+
await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody);
706710

707711
// Assert
708712
server
@@ -740,6 +744,103 @@ public async Task HaveReceived1Call_WithBodyAsJson()
740744
server.Stop();
741745
}
742746

747+
[Fact]
748+
public async Task WithBodyAsJson_When_NoMatch_ShouldHaveCorrectErrorMessage()
749+
{
750+
// Arrange
751+
var server = WireMockServer.Start();
752+
753+
server
754+
.Given(Request.Create().WithPath("/a").UsingPost())
755+
.RespondWith(Response.Create().WithBody("A response"));
756+
757+
// Act
758+
var httpClient = new HttpClient();
759+
760+
var requestBody = new
761+
{
762+
x = "123"
763+
};
764+
await httpClient.PostAsJsonAsync($"{server.Url}/a", requestBody);
765+
766+
// Assert
767+
Action act = () => server
768+
.Should()
769+
.HaveReceived(1)
770+
.Calls()
771+
.WithBodyAsJson(new { x = "y" })
772+
.And
773+
.UsingPost();
774+
775+
act.Should()
776+
.Throw<Exception>()
777+
.WithMessage("""Expected wiremockserver to have been called using body "{"x":"y"}", but didn't find it among the body/bodies "{"x":"123"}".""");
778+
779+
server.Stop();
780+
}
781+
782+
[Fact]
783+
public async Task WithBodyAsString_When_NoMatch_ShouldHaveCorrectErrorMessage()
784+
{
785+
// Arrange
786+
var server = WireMockServer.Start();
787+
788+
server
789+
.Given(Request.Create().WithPath("/a").UsingPost())
790+
.RespondWith(Response.Create().WithBody("A response"));
791+
792+
// Act
793+
var httpClient = new HttpClient();
794+
795+
await httpClient.PostAsync($"{server.Url}/a", new StringContent("123"));
796+
797+
// Assert
798+
Action act = () => server
799+
.Should()
800+
.HaveReceived(1)
801+
.Calls()
802+
.WithBody("abc")
803+
.And
804+
.UsingPost();
805+
806+
act.Should()
807+
.Throw<Exception>()
808+
.WithMessage("""Expected wiremockserver to have been called using body "abc", but didn't find it among the body/bodies "123".""");
809+
810+
server.Stop();
811+
}
812+
813+
[Fact]
814+
public async Task WithBodyAsBytes_When_NoMatch_ShouldHaveCorrectErrorMessage()
815+
{
816+
// Arrange
817+
var server = WireMockServer.Start();
818+
819+
server
820+
.Given(Request.Create().WithPath("/a").UsingPost())
821+
.RespondWith(Response.Create().WithBody("A response"));
822+
823+
// Act
824+
var httpClient = new HttpClient();
825+
826+
await httpClient.PostAsync($"{server.Url}/a", new ByteArrayContent(new byte[] { 5 }));
827+
828+
// Assert
829+
Action act = () => server
830+
.Should()
831+
.HaveReceived(1)
832+
.Calls()
833+
.WithBodyAsBytes(new byte[] { 1 })
834+
.And
835+
.UsingPost();
836+
837+
act.Should()
838+
.Throw<Exception>()
839+
.WithMessage("""Expected wiremockserver to have been called using body "byte[1] {...}", but didn't find it among the body/bodies "byte[1] {...}".""");
840+
841+
server.Stop();
842+
}
843+
743844
[Fact]
744845
public async Task HaveReceived1Call_WithBodyAsBytes()
745846
{

0 commit comments

Comments
 (0)