Good Unit Tests when ReSharper bugs for null checks 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 and viewModel.




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.
Asserting

if (viewModel != null) Assert.IsInstanceOfType(viewModel.GetType(), typeof(DraftViewModel));


You should use another assert and not an if
Assert.IsNotNull(viewModel);

Resharper even suggests this option:

Test name

Create_DraftFacade_ViewResultWithDraftViewModel


You might also want to reconsider the naming of your tests. Usually we use this pattern

TestedMethod/Property_TestData/Case_ExpectedResult