Skip to content

Commit

Permalink
Use JSON source generator in WebApplicationFactory (#55595)
Browse files Browse the repository at this point in the history
Use JSON source generator to deserialize dictionary.
Resolves #55586.
  • Loading branch information
martincostello authored Jun 26, 2024
1 parent 4c8b5fe commit 9425978
Showing 1 changed file with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/Mvc/Mvc.Testing/src/WebApplicationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Net.Http;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.TestHost;
Expand All @@ -21,7 +22,7 @@ namespace Microsoft.AspNetCore.Mvc.Testing;
/// </summary>
/// <typeparam name="TEntryPoint">A type in the entry point assembly of the application.
/// Typically the Startup or Program classes can be used.</typeparam>
public class WebApplicationFactory<TEntryPoint> : IDisposable, IAsyncDisposable where TEntryPoint : class
public partial class WebApplicationFactory<TEntryPoint> : IDisposable, IAsyncDisposable where TEntryPoint : class
{
private bool _disposed;
private bool _disposedAsync;
Expand Down Expand Up @@ -235,7 +236,7 @@ private void SetContentRoot(IWebHostBuilder builder)

private static string? GetContentRootFromFile(string file)
{
var data = JsonSerializer.Deserialize<IDictionary<string, string>>(File.ReadAllBytes(file))!;
var data = JsonSerializer.Deserialize(File.ReadAllBytes(file), CustomJsonSerializerContext.Default.IDictionaryStringString)!;
var key = typeof(TEntryPoint).Assembly.GetName().FullName;

// If the `ContentRoot` is not provided in the app manifest, then return null
Expand All @@ -248,6 +249,9 @@ private void SetContentRoot(IWebHostBuilder builder)
return (contentRoot == "~") ? AppContext.BaseDirectory : contentRoot;
}

[JsonSerializable(typeof(IDictionary<string, string>))]
private sealed partial class CustomJsonSerializerContext : JsonSerializerContext;

private string? GetContentRootFromAssembly()
{
var metadataAttributes = GetContentRootMetadataAttributes(
Expand Down

0 comments on commit 9425978

Please sign in to comment.