I have edited and simplified this question a lot.
If I have this method on my HomeController:
public ActionResult Strangeness( int id )
{
StrangenessClass strangeness = null;
if( id == 1 )
{
strangeness = new StrangenessClass() { Name="Strangeness", Desc="Really weird behavior" };
}
return View( strangeness );
}
And have this class:
public class StrangenessClass
{
public string Name { get; set; }
public string Desc { get; set; }
}
Why does this unit test fail?
[TestMethod]
public void Strangeness()
{
HomeController controller = new HomeController();
ViewResult result = controller.Strangeness( 1 ) as ViewResult;
var model = result.ViewData.Model;
result = controller.Strangeness( 2 ) as ViewResult;
model = result.ViewData.Model;
Assert.IsNull( model );
}
I understand that normally, I would have one test to test the null condition and another to test a good condition, but I ran into this problem while testing my delete controller. On a delete test, I would normally fetch the record, delete the record, and then attempt to fetch it again. It should be null the second time I fetch it, but it wasn’t. So, I boiled the problem down as described above.
If this is not the proper way to test deletes, how would you do it? Don’t you need to make sure that the record was actually deleted?
You should not reuse a controller to handle multiple requests, which is exactly what you are doing here.
Anyway, if you check the source code for MVC you’ll find the reason for this behavior:
If the model is null, it’s not assigned to the ViewData.Model property.
If you want the correct behaviour, create a new controller for your second call to
HomeController.Strangeness.