I am pretty new to testing and have been writing my Controller tests as follows:
var result = myController.Create(It.IsAny<int>());
Assert.IsInstanceOfType(result, typeof(ViewResult));
Assert.AreEqual(string.Empty, ((ViewResult)result).ViewName, "Default view expected.");
Assert.IsInstanceOfType(((ViewResult)result).ViewData.Model, typeof(FooBarCreateEditViewModel));
This works fine but is not as readable in that I am having to perform a cast for Tests 2 & 3. An alternative approach might be to do the following:
var result = (ViewResult)myController.Create(It.IsAny<int>());
Assert.AreEqual(string.Empty, result.ViewName, "Default view expected.");
Assert.IsInstanceOfType(result.ViewData.Model, typeof(FooBarCreateEditViewModel));
This also seems to work and is more readable in my opinion. My problem with it is that it relies on the “act” part of the test to perform the IsInstanceOfType test, rather than explicitly defining an Assert to do the job.
So is my second apporach ok to continue with? I am likely to run into issues with relying on the cast to throw an error should the method return a different type?
You could use MVCContrib.TestHelper. Allows you to write very readable unit tests like:
Checkout the following sample unit test I wrote.