Skip to content

Instantly share code, notes, and snippets.

@odan
Created September 6, 2025 13:09
Show Gist options
  • Save odan/7022f7ee29cbf25b3315a7b11efb7913 to your computer and use it in GitHub Desktop.
Save odan/7022f7ee29cbf25b3315a7b11efb7913 to your computer and use it in GitHub Desktop.
C# HTTP test with Json
using System.Text.Json.Nodes;
using System.Xml.Linq;
namespace Test.TestCase;
public class HttpTest
{
private ApplicationFactory _factory { get; set; }
private ClientAuth _clientAuth { get; set; }
private TestDatabase _db { get; set; }
public HttpTest(
ApplicationFactory factory,
ClientAuth clientAuth,
TestDatabase db
)
{
_db = db;
_factory = factory;
_clientAuth = clientAuth;
}
[Fact]
public async Task TestGetCustomers()
{
// Arrange
var client = _factory.CreateClient();
_clientAuth.AddBasicAuthHeaders(client);
// Act
var response = await client.GetAsync("/api/customers");
// Assert
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType?.ToString());
}
[Fact]
public async Task TestPostCustomer()
{
// Arrange
var client = _factory.CreateClient();
_clientAuth.AddBasicAuthHeaders(client);
// Act
var payload = new
{
first_name = "Max",
last_name = "Meier"
};
var content = TestJson.Content(payload);
var response = await client.PostAsync("/api/customers", content);
// Assert
Assert.Equal(HttpStatusCode.Created, response.StatusCode);
var json = await response.Content.ReadAsStringAsync();
var expected = new
{
customer_id = "1",
};
JsonAssert.Equal(expected, json);
}
}
using System.Text.Json.Nodes;
namespace Test
{
public static class JsonAssert
{
public static void Equal(object expected, string actualJson)
{
var expectedNode = JsonSerializer.SerializeToNode(expected);
var actualNode = JsonNode.Parse(actualJson);
if (JsonNode.DeepEquals(actualNode, expectedNode))
{
return;
}
var actualElement = JsonSerializer.Deserialize<object>(actualJson);
var expectedJson = JsonSerializer.Serialize(expected);
var expectedElement = JsonSerializer.Deserialize<object>(expectedJson);
Assert.Equal(expectedElement, actualElement);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment