Use RazorEngine to perform UnitTest on Views of ASP. net mvc,
Sometimes we need to perform unit tests on the final text produced by Razor (html or xml or.
Use Nuget to install RazorEngine.
Create an ASP. net mvc project with a test project.
Modify Index. cshtml
@using TestRazor.Models@model TestModel<div>This is a test page</div><div>Name @Model.Name </div><div>Age @Model.Age</div>
Test:
[TestClass] public class HomeControllerTest {[TestMethod] public void Index () {var config = new TemplateServiceConfiguration (); config. debug = true; using (StreamReader sr = File. openText (@ "E: \ temporary \ 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 );}}}}
Result:
Bingo!