gpt4 book ai didi

c# - 如何在 ASP.NET Core MVC 中对 RazorViewEngineOptions 进行单元测试?

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:54 26 4
gpt4 key购买 nike

在从 ConfigureServices 调用的扩展方法中我正在添加 EmbeddedFileProvider 的实例至 RazorViewEngineOptions .我想测试它是否已添加,但我找不到如何获取 RazorViewEngineOptions实例。

这在应用程序运行时有效:

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddMyServices(Configuration);
}
public static IServiceCollection AddMyServices(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(new EmbeddedFileProvider(typeof(MyClass).Assembly, "My.Namespace"));
});

return services;
}

但是我该如何测试呢? NullReferenceException被扔在这里:

[Fact]
public void MyTest()
{
var services = new ServiceCollection();
var serviceProvider = services.BuildServiceProvider();

MyServicesBuilder.AddMyServices(services, new Mock<IConfiguration>().Object);
var razorOptions = serviceProvider.GetService<IOptions<RazorViewEngineOptions>>();

Assert.Equal(1, razorOptions.Value.FileProviders.Where(x => x.GetType() == typeof(EmbeddedFileProvider)).Count());
}

我试过添加 services.AddMvc()services.AddSingleton<RazorViewEngineOptions>() .

我也试过调用 services.GetRequiredService<RazorViewEngineOptions>()但这会抛出 System.InvalidOperationException : No service for type 'Microsoft.Extensions.Options.IOptions'1[Microsoft.AspNetCore.Mvc.Razor.RazorViewEngineOptions

我也尝试过询问 RazorViewEngineOptions而不是 IOptions<RazorViewEngineOptions> .

最佳答案

在构建提供者之后添加到服务集合的任何内容,提供者都不会知道。

将所需的一切添加到服务集合中,然后才构建提供者来执行您的断言

例如

[Fact]
public void MyTest() {
//Arrange
var services = new ServiceCollection();
services.AddOptions();

IConfiguration config = new ConfigurationBuilder()
// Call additional providers here as needed.
//...
.Build();

//Act
MyServicesBuilder.AddMyServices(services, config);
//OR
//services.AddMyServices(config);

//Assert
var serviceProvider = services.BuildServiceProvider();
var razorOptions = serviceProvider.GetService<IOptions<RazorViewEngineOptions>>();

Assert.NotNull(razorOptions);
Assert.Equal(1, razorOptions.Value.FileProviders.Where(x => x.GetType() == typeof(EmbeddedFileProvider)).Count());
}

关于c# - 如何在 ASP.NET Core MVC 中对 RazorViewEngineOptions 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55418800/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com