Enigmatry.Entry.AspNetCore.Tests.SystemTextJson 9.1.1-preview.3

This is a prerelease version of Enigmatry.Entry.AspNetCore.Tests.SystemTextJson.
dotnet add package Enigmatry.Entry.AspNetCore.Tests.SystemTextJson --version 9.1.1-preview.3
                    
NuGet\Install-Package Enigmatry.Entry.AspNetCore.Tests.SystemTextJson -Version 9.1.1-preview.3
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Enigmatry.Entry.AspNetCore.Tests.SystemTextJson" Version="9.1.1-preview.3" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Enigmatry.Entry.AspNetCore.Tests.SystemTextJson" Version="9.1.1-preview.3" />
                    
Directory.Packages.props
<PackageReference Include="Enigmatry.Entry.AspNetCore.Tests.SystemTextJson" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Enigmatry.Entry.AspNetCore.Tests.SystemTextJson --version 9.1.1-preview.3
                    
#r "nuget: Enigmatry.Entry.AspNetCore.Tests.SystemTextJson, 9.1.1-preview.3"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#addin nuget:?package=Enigmatry.Entry.AspNetCore.Tests.SystemTextJson&version=9.1.1-preview.3&prerelease
                    
Install Enigmatry.Entry.AspNetCore.Tests.SystemTextJson as a Cake Addin
#tool nuget:?package=Enigmatry.Entry.AspNetCore.Tests.SystemTextJson&version=9.1.1-preview.3&prerelease
                    
Install Enigmatry.Entry.AspNetCore.Tests.SystemTextJson as a Cake Tool

ASP.NET Core Tests System.Text.Json

A library that provides testing utilities for ASP.NET Core applications using System.Text.Json as the JSON serialization provider.

Intended Usage

Use this library when testing ASP.NET Core applications that use System.Text.Json for JSON serialization. It provides helper methods for serializing and deserializing test data, as well as utilities for working with HTTP requests and responses.

Installation

Add the package to your project:

dotnet add package Enigmatry.Entry.AspNetCore.Tests.SystemTextJson

Usage Examples

Deserializing HTTP Response Content

using Enigmatry.Entry.AspNetCore.Tests.SystemTextJson.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using NUnit.Framework;

[TestFixture]
public class HttpResponseDeserializationTests
{
    private readonly HttpClient _httpClient;

    public HttpResponseDeserializationTests()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("https://api.example.com/");
    }    [Test]
    public async Task DeserializeAsync_DeserializesResponseContent()
    {
        // Arrange & Act
        var response = await _httpClient.GetAsync("api/products");
        
        // Assert
        // DeserializeAsync doesn't check status code, just deserializes content        var products = await response.DeserializeAsync<List<Product>>();
        Assert.That(products, Is.Not.Null);
        Assert.That(products, Is.Not.Empty);
    }    [Test]
    public async Task DeserializeWithStatusCodeCheckAsync_ThrowsOnNonSuccessStatus()
    {
        // Arrange & Act
        var response = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
        response.Content = new StringContent("Product not found");
        response.RequestMessage = new HttpRequestMessage(HttpMethod.Get, "api/products/999");
        
        // Assert
        // DeserializeWithStatusCodeCheckAsync will throw if status code is not success        Assert.ThrowsAsync<HttpRequestException>(async () => 
            await response.DeserializeWithStatusCodeCheckAsync<Product>());
    }    [Test]
    public async Task EnsureSuccessStatusCodeAsync_ThrowsWithDetailedMessage()
    {
        // Arrange
        var response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
        response.Content = new StringContent("Invalid request parameters");
        response.RequestMessage = new HttpRequestMessage(HttpMethod.Get, "api/products");
        
        // Act & Assert
        // EnsureSuccessStatusCodeAsync enhances exception with content details        var exception = Assert.ThrowsAsync<HttpRequestException>(async () => 
            await response.EnsureSuccessStatusCodeAsync());
            
        Assert.That(exception.Message, Does.Contain("StatusCode: BadRequest"));
        Assert.That(exception.Message, Does.Contain("Invalid request parameters"));
    }
      [Test]
    public async Task TestResponseAssertions_UsingAssertionExtensions()
    {
        // Arrange
        var badRequestResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
        var notFoundResponse = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
        
        var validationResponse = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest);
        validationResponse.Content = new StringContent(@"{
            ""type"": ""https://tools.ietf.org/html/rfc7231#section-6.5.1"",
            ""title"": ""One or more validation errors occurred."",
            ""status"": 400,
            ""errors"": {
                ""Name"": [""The Name field is required.""]
            }
        }");
        
        // Act & Assert
        // Use the assertion extension methods
        badRequestResponse.BeBadRequest();
        notFoundResponse.BeNotFound();
        validationResponse.ContainValidationError("Name", "required");
    }
}

Configuring JSON Serialization Options

The library uses a centralized HttpSerializationOptions class for configuring System.Text.Json serialization. By default, it's configured with PropertyNameCaseInsensitive = true to make JSON property mapping case-insensitive.

using Enigmatry.Entry.AspNetCore.Tests.SystemTextJson.Http;
using System.Text.Json;
using System.Text.Json.Serialization;

// Configure the global JSON serialization settings
HttpSerializationOptions.Options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    WriteIndented = true,
    DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
    Converters = 
    {
        new JsonStringEnumConverter()
    }
};

// These options will be used by all the extension methods in the library
// for both serialization and deserialization

## How It Works

The Enigmatry.Entry.AspNetCore.Tests.SystemTextJson library provides a set of extension methods that makes testing ASP.NET Core applications using System.Text.Json easier. Here's how the components work together:

1. **HttpResponseMessageExtensions** provides methods to deserialize HTTP responses with proper error handling.

2. **JsonHttpClientExtensions** simplifies making HTTP requests and handling responses, with automatic serialization of request bodies and deserialization of response bodies.

3. **HttpResponseMessageAssertionsExtensions** provides fluent assertions for testing HTTP responses, especially useful for validating error responses and validation errors.

4. **HttpSerializationOptions** provides a central place to configure JSON serialization options that are used throughout the library.

## Project Dependencies

This library depends on:
- System.Text.Json for JSON serialization
- Microsoft.AspNetCore.Mvc for ValidationProblemDetails
- System.Net.Http.Json for HTTP client integrations
- Shouldly for assertions

It's designed to work with XUnit, NUnit, or MSTest for testing ASP.NET Core applications.

Using HTTP Client Extensions

using Enigmatry.Entry.AspNetCore.Tests.SystemTextJson.Http;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using NUnit.Framework;

[TestFixture]
public class HttpClientExtensionsTests
{
    private readonly HttpClient _httpClient;

    public HttpClientExtensionsTests()
    {
        _httpClient = new HttpClient();
        _httpClient.BaseAddress = new Uri("https://api.example.com/");
    }

    [Fact]
    public async Task GetAsync_SimplifiesHttpGetWithDeserialization()
    {
        // GetAsync combines HTTP request and deserialization with status code check
        var product = await _httpClient.GetAsync<Product>("api/products/1");
        
        // Result is automatically deserialized and status checked
        Assert.NotNull(product);
        Assert.Equal(1, product.Id);
    }
    
    [Fact]
    public async Task GetAsync_WithParameters_AppendsQueryParameters()
    {
        // Using GetAsync with URI parameters
        var products = await _httpClient.GetAsync<List<Product>>(
            new Uri("https://api.example.com/api/products"), 
            new KeyValuePair<string, string>("category", "electronics"),
            new KeyValuePair<string, string>("inStock", "true")
        );
        
        Assert.NotNull(products);
        Assert.NotEmpty(products);
    }
    
    [Fact]
    public async Task PostAsync_SimplifiesHttpPostWithSerialization()
    {
        // Create a product to send
        var newProduct = new Product { Name = "New Product", Price = 19.99m };
        
        // PostAsync without response
        await _httpClient.PostAsync("api/products", newProduct);
        
        // PostAsync with typed response
        var createdProduct = await _httpClient.PostAsync<Product, Product>("api/products", newProduct);
        
        Assert.NotNull(createdProduct);
        Assert.NotEqual(0, createdProduct.Id);
    }
    
    [Fact]
    public async Task PutAsync_SimplifiesHttpPutWithSerialization()
    {
        // Create a product to update
        var updatedProduct = new Product { Id = 1, Name = "Updated Product", Price = 29.99m };
        
        // PutAsync without response
        await _httpClient.PutAsync("api/products/1", updatedProduct);
        
        // PutAsync with typed response
        var result = await _httpClient.PutAsync<Product, Product>("api/products/1", updatedProduct);
        
        Assert.NotNull(result);
    }
}
Product Compatible and additional computed target framework versions.
.NET net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
9.1.1-preview.3 98 6/4/2025
9.1.0 122 6/3/2025
9.0.1-preview.8 112 5/26/2025
9.0.1-preview.7 200 5/13/2025
9.0.1-preview.6 140 5/9/2025
9.0.1-preview.5 133 5/7/2025
9.0.1-preview.4 113 4/30/2025
9.0.1-preview.2 118 4/1/2025
9.0.0 227 2/26/2025
8.1.1-preview.3 114 5/7/2025
8.1.1-preview.1 118 4/1/2025
8.1.0 320 2/19/2025
8.0.1-preview.4 62 2/7/2025
8.0.1-preview.2 50 1/15/2025
8.0.0 858 11/27/2024
3.4.6-preview.10 60 11/27/2024
3.4.3 1,105 10/22/2024
3.4.2 2,063 10/11/2024
3.4.1 122 10/9/2024
3.4.0 109 10/9/2024
3.3.2 460 8/28/2024
3.3.2-preview.7 84 8/27/2024
3.3.1 374 7/16/2024
3.3.1-preview.4 64 7/12/2024
3.3.0 1,126 6/20/2024
3.2.1-preview.4 60 6/17/2024
3.2.1-preview.1 70 5/23/2024
3.2.0 1,857 4/3/2024
3.1.1-preview.1 1,001 3/13/2024
3.1.0 327 3/8/2024
3.1.0-preview.2 309 2/19/2024
3.0.1-preview.2 906 2/9/2024
3.0.1-preview.1 77 1/24/2024
3.0.0 953 1/15/2024
3.0.0-preview.14 110 1/9/2024
3.0.0-preview.12 71 1/9/2024
3.0.0-preview.5 77 1/10/2024
3.0.0-preview.2 136 12/28/2023
3.0.0-preview 138 12/20/2023
2.1.0 183 12/28/2023
2.0.1-preview.3 104 12/1/2023
2.0.1-preview.2 87 11/29/2023
2.0.1-preview.1 81 11/28/2023
2.0.0 310 11/8/2023
2.0.0-preview.3 281 10/27/2023
2.0.0-preview.2 74 10/27/2023
2.0.0-preview.1 80 10/27/2023
2.0.0-preview 129 10/27/2023
1.1.500 161 10/27/2023
1.1.495 197 9/24/2023
1.1.486 436 9/13/2023
1.1.484 202 9/7/2023
1.1.482 152 9/6/2023
1.1.480 177 8/24/2023
1.1.477 401 8/2/2023
1.1.464 197 7/5/2023
1.1.447 661 5/26/2023
1.1.396 236 4/11/2023
1.1.383 268 4/3/2023
1.1.377 254 3/13/2023
1.1.376 252 3/13/2023
1.1.365 687 2/15/2023