.NET WireMock reject PostAsJsonAsync serialization

27 Views Asked by At

I have a WireMock API setup for testing purposes. First, I was using the short way to make a REST call to my WireMock endpoint:

var response = await _httpClient.PostAsJsonAsync("resorce/someRoute", obj);

This simply didn't work and I always got a "Not Found" response. After a lot of debugging without finding any issues regarding my REST calls and my WireMock setup, I tried the verbose way of doing the same functionality:

var json = new StringContent(JsonSerializer.Serialize(obj),
    Encoding.UTF8, "application/json");

var response = await _httpClient.PostAsync("resorce/someRoute", json);

This time it worked! According to my information, both do the same thing.

What is the problem here? Is it a WireMock thing or PostAsJsonAsync may lead to different behaviour?

Here is a short code example

1

There are 1 best solutions below

1
Guru Stron On BEST ANSWER

PostAsJsonAsync uses JsonSerializerDefaults.Web for serializer options which will result in Camel case property names in the JSON while JsonSerializer.Serialize(obj) will use default ones resulting in Pascal case (matching property names). There are multiple ways to handle that. For example changing the settings for PostAsJsonAsync:

var response = await httpCLient.PostAsJsonAsync("/hello-world", obj, new JsonSerializerOptions());

Or using the Camel case for the object:

_server.Given(
    Request.Create()
        .WithPath("/hello-world")
        .UsingPost()
        .WithBodyAsJson(new { command = "Say hello"} ))