I have the latest version of ReSharper installed and I am trying to write a Unit Test for my MVC controller. I need the Unit Test to:
Ensure the ViewModel passed to the View is of the correct type.
So here is what I have at the moment:
public void Create_HasCorrectViewModelType()
{
// arrange
var controller = new DraftController(_draftFacade);
// act
var viewResult = controller.Create() as ViewResult;
var viewModel = viewResult.Model as DraftViewModel;
// assert
Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));
}
I have issues with this, and would like to know your thoughts on the matter.
- the arrange makes sense. I am arranging / setting up my controller.
- Only the first line in the act seems logical to me. But me trying to grab the ViewModel isn't really an Act is it? Sounds like
// arrange
again! - ReSharper complains that I am not doing null checks on
viewResult
andviewModel
.
I can go with ReSharper's recommendation, then my test becomes:
public void Create_HasCorrectViewModelType()
{
// arrange
var controller = new DraftController(_draftFacade);
// act
var viewResult = controller.Create() as ViewResult;
var viewModel = viewResult?.Model as DraftViewModel;
// assert
if (viewModel != null) Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));
}
Now ReSharper is happy, but then my Unit Test don't seem clean anymore! I feel like there are too many paths that can be taken for that one unit test.
Anyone else bugged by this? What can I do to improve this? Or is this the best I'm going to get?
Any help would be greatly appreciated.
Assert.IsInstanceOf<DraftViewModel>(viewResult?.Model);
? \$\endgroup\$viewModel
that's only going to be populated ifModel
is castable to aDraftViewModel
. Doing the same thing in your assert is redundant, you could just be asserting thatviewModel != null
. In your refactored, 'resharper friendly' approach you're going to get a pass ifviewModel
is null, which feels wrong. The approach I'm suggesting gets rid of the unnecessary variable and gives you a single line assert that confirms all of the expected linkages. If you don't care about them, then ignore resharper, you know the context better than it does. \$\endgroup\$