I use templated helpers in an ASP.NET MVC 3 project. One display template had a typo — an accidental extra code block — that caused a compiler error when that view was returned (“Don’t put @if in a code block,” you know).
All fine, except that the test method that called that view was still succeeding. I’m having a hard time figuring out how I would fail this code block in a unit test.
Here’s the bad display template:
@model MemberSelectorViewModel
@{
Layout = "~/Views/Shared/_DisplayFormItem.cshtml";
}
@section DataContent {
@{ // <- this was the typo, and it...
@if (Model.idMember.HasValue) // <- causes this to throw a compiler error
{
@Html.ActionLink(Model.FullName, "Details", "Member", new { id = Model.idMember.Value }, null )
@Html.HiddenFor(m=> m.idMember)
}
}
}
Here’s the test that I think ought to be failing:
[TestMethod]
public void DetailsReturnsView()
{
MemberJobController target = new MemberJobController(TestHarness.Context);
memberjob mj = TestHarness.UnitOfWork.MemberJobRepository.FirstOrDefault(x => true);
ActionResult result = target.Details(mj.idmemberjob); // <- this should hit the compiler error, I would have thought
Assert.IsNotNull(result);
}
But that test succeeds.
Any idea how I’d write a test that would fail on the ” @{ @if () ” typo in a templated helper?
I think you might have misunderstood something about how unit tests work on a controller. They never hit the view actually. So no matter how many errors you did in your view, when you call the controller action in a unit test, all that happens is that the body of this action is executed. And that’s all. It will never go to the view.
So if you want to test your views you are no longer doing unit tests. You are doing integration tests where you send an HTTP request to your site which is deployed on a staging server and verifying that the returned HTML complies to your requirements. In this case if you made a typo or something in your view the actual HTML which is returned when you hit the particular controller action with an HTTP request will obviously differ than what you expect.