RazorViewEngineOptions

RazorViewEngineOptions

在从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/

10-12 01:20