有的时候我们需要对Razor最后生产的文本(HTML OR XML OR..)进行单元测试。
使用Nuget安装RazorEngine。
新建一个ASP.NET MVC项目,并且带有测试项目。
修改Index.cshtml
@using TestRazor.Models
@model TestModel <div>This is a test page</div> <div>Name @Model.Name </div>
<div>Age @Model.Age</div>
测试:
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void Index()
{
var config = new TemplateServiceConfiguration();
config.Debug = true;
using (StreamReader sr = File.OpenText(@"E:\临时\TestRazor\TestRazor\Views\Home\Index.cshtml"))
{
var template = sr.ReadToEnd();
using (var service = RazorEngineService.Create(config))
{
var html = service.RunCompile(template, "test", null, new TestModel
{
Name = "kklldog",
Age = 10
}); Assert.IsTrue(html.Contains("This is a test page"));
Assert.IsTrue(html.Contains("Name kklldog"));
Assert.IsTrue(html.Contains("Age 10"));
Console.WriteLine(html);
}
}
} }
结果:
bingo!