You can get this method for testing with slight modifications. To test this, you need to change your SUT (System Under Test) so that it becomes more verifiable. It is always useful to change the SUT to make the API more verifiable, even once it looked a little weird.
There are criminals in your SUT that are harder to test. but.
using (var sw = new StringWriter())
b. (inside RenderRazorViewToString)
ViewEngines.Engines.FindPartialView(ControllerContext, "Index");
With StringWriter, you need to access the running StringWriter test so that you have control over what the view of this author was written.
With FindPartialView, ViewEnginesCollection is a static collection in ViewEngines, and FindPartialView has many things that happen at the bottom, and it seems harder to drown. Perhaps there is another way, since FindPartialView is virtual, so we can insert a muted ViewEngine that we could mute the FindPartialView method. But I am not able to stifle / mock the whole universe, so I took a different approach, but still performs this task. This is by introducing a delegate, so I have full control over what FindPartialView returned.
System Test (SUT)
public class HomeController : Controller { public Func<ViewEngineResult> ViewEngineResultFunc { get; set; } public Func<StringWriter> StringWriterFunc { get; set; } public HomeController() { ViewEngineResultFunc = () => ViewEngines.Engines.FindPartialView(ControllerContext, "Index"); } private string RenderRazorViewToString(string viewName, object model) { ViewData.Model = model; using (var sw = new StringWriter()) { StringWriter stringWriter = StringWriterFunc == null ? sw : StringWriterFunc(); var viewResult = ViewEngineResultFunc(); var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, stringWriter); viewResult.View.Render(viewContext, stringWriter); viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); return stringWriter.GetStringBuilder().ToString(); } } public ActionResult StringIndex() { string result = RenderRazorViewToString("Index", null); return Content(result); }
As you can see, there are two delegates for StringWriter, StringWriterFunc is called, and the other is for FindPartialView, which is called ViewEngineResultFunc.
During the actual execution of the program, these delegates should use real instances where, like during the test, they are replaced with fake instances.
Unit test
[TestClass] public class HomeControllerTest { [TestMethod] public void StringIndex_RenderViewToString_ContentResuleContainsExpectedString() {