mockhttp icon indicating copy to clipboard operation
mockhttp copied to clipboard

Relax WithJsonContent

Open atrauzzi opened this issue 10 months ago • 1 comments

I suspect WithJsonContent is a bit too strict as it requires that properties appear in the exact same order.

This makes it difficult to develop tests if what I'm handing the HttpClient to isn't my own code and I have no control over how it will choose to serialize things.

Also, it would be nice if the MockHttpMatchException included what it received. Not just what it's expecting.

atrauzzi avatar Mar 09 '25 08:03 atrauzzi

Here is simple workaround if you use Newtonsoft:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RichardSzalay.MockHttp;

public static class MockHttpMessageHandlerExtensions {
    /// <summary>
    ///     Allows to partially match json payload (it expects objects on both sides: expected request and matching request)
    /// </summary>
    public static MockedRequest WithPartialJsonContent<TPayload>(this MockedRequest request, TPayload payload) {
        var stringPayload = JsonConvert.SerializeObject(payload);
        var objectPayload = JsonConvert.DeserializeObject<JObject>(stringPayload)!;

        return request.WithJsonContent<object>(t => {
            var tObject = JsonConvert.DeserializeObject<JObject>(t.ToString()!)!;

            foreach (var property in objectPayload.Properties()) {
                if (tObject.Property(property.Name) is not { } property2) {
                    return false;
                }

                if (!JToken.DeepEquals(property.Value, property2.Value)) {
                    return false;
                }
            }

            return true;
        });
    }
}

samnung avatar Jun 13 '25 19:06 samnung