在从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>
。
答案 0 :(得分:0)
提供者已经建立之后,添加到服务集合的任何内容都不会被提供者知道。
将所需的所有内容添加到服务集合中,然后构建提供程序以执行您的断言
例如
[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());
}