我需要渲染一个字符串的视图(作为电子邮件发送)。我正在使用this implementation。
我想对它进行单元测试,而不需要完整的ASP.NET Core环境。所以我必须创建一个IRazorViewEngine
。
默认实施是RazorViewEngine
。 I has a mega constructor因为每个参数都需要创建,每个参数都有一个巨型构造函数等等(我不能嘲笑它,我需要一个实时实例。)
当然有一种更简单的获取实例的方法吗?
(在Core之前,我可以使用ViewEngines.Engines
。也许Core有类似的东西?)
答案 0 :(得分:0)
我也尝试通过与此类似的单元测试来做到这一点,并遇到各种问题:
var services = new ServiceCollection();
services.AddMvc();
... ended up needing to add random things into the service collection ...
var serviceProvider = services.BuildServiceProvider();
var razorViewEngine = serviceProvider.GetRequiredService<IRazorViewEngine>();
我最终使用Microsoft.AspNetCore.Mvc.Testing使用了更多的组件测试方法:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public class ComponentTestStartup : IStartup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddMvc();
return services.BuildServiceProvider();
}
public void Configure(IApplicationBuilder app)
{
}
}
public class ComponentTestServerFixture : WebApplicationFactory<ComponentTestStartup>
{
public TService GetRequiredService<TService>()
{
if (Server == null)
{
CreateDefaultClient();
}
return Server.Host.Services.GetRequiredService<TService>();
}
protected override IWebHostBuilder CreateWebHostBuilder()
{
var hostBuilder = new WebHostBuilder();
return hostBuilder.UseStartup<ComponentTestStartup>();
}
// uncomment if your test project isn't in a child folder of the .sln file
// protected override void ConfigureWebHost(IWebHostBuilder builder)
// {
// builder.UseSolutionRelativeContentRoot("relative/path/to/test/project");
// }
}
public class RazorViewToStringRendererTests
{
private readonly RazorViewToStringRenderer viewRenderer;
public RazorViewToStringRendererTests()
{
var server = new ComponentTestServerFixture();
var serviceProvider = server.GetRequiredService<IServiceProvider>();
var viewEngine = server.GetRequiredService<IRazorViewEngine>();
var tempDataProvider = server.GetRequiredService<ITempDataProvider>();
viewRenderer = new RazorViewToStringRenderer(viewEngine, tempDataProvider, serviceProvider);
}
[Fact]
public async Task CanRenderViewToString()
{
// arrange
var model = "test model";
// act
var renderedView = await viewRenderer.RenderViewToStringAsync("/Path/To/TestView.cshtml", model);
// assert
Assert.NotNull(renderedView);
Assert.Contains(model, renderedView, StringComparison.OrdinalIgnoreCase);
}
}
TestView.cshtml:
@model string
<h1>@Model</h1>