要进行Asp.net Core MVC - Razor视图的单元测试,可以使用以下解决方法:
using Xunit;
using Microsoft.AspNetCore.Mvc.Testing;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Razor.Compilation;
namespace YourNamespace.Tests
{
public class RazorViewTests : IClassFixture>
{
private readonly WebApplicationFactory _factory;
public RazorViewTests(WebApplicationFactory factory)
{
_factory = factory;
}
[Fact]
public async Task RazorView_ReturnsExpectedContent()
{
// Arrange
var client = _factory.CreateClient();
// Act
var response = await client.GetAsync("/YourController/YourAction");
// Assert
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("Expected content", content); // Replace "Expected content" with the expected content from the Razor view
}
[Fact]
public void RazorView_CompilesWithoutErrors()
{
// Arrange
var compilationOptionsProvider = _factory.Services.GetService(typeof(IViewCompilerProvider)) as IViewCompilerProvider;
// Act
var compiler = compilationOptionsProvider.GetCompiler();
var result = compiler.CompileViews(typeof(YourStartupClass));
// Assert
Assert.Empty(result);
}
}
}
以上示例代码可以用于对Asp.net Core MVC中的Razor视图进行单元测试。确保你的项目中已经正确配置了Razor视图,并且视图的内容和编译没有问题。