I use the same controller instance in all of my tests, and just discovered (because my tests run in an arbitrary order) that if you call Controller.View with no arguments, it will pass back the same ViewDataDictionary that was created by a previous call to Controller.View which had arguments!
A trivial example (with NUnit and MvcContrib)
<Test()> _
Public Sub Test_A()
Dim r As ViewResult = MockController.MethodWhichReturnsViewData().AssertViewRendered()
Assert.IsNotNull(r.Model)
End Sub
<Test()> _
Public Sub Test_B()
Dim r As ViewResult = MockController.MethodWhichDoesNotReturnViewData().AssertViewRendered()
Assert.IsNull(r.Model) '<==== fails, has the same view data as Test_A!
End Sub
This is bad for my tests (obviously). I can imagine two solutions, neither of which I like, any suggestions? (As a bonus, can anyone understand why MS designed it this way?)
- Explicitly specify
Nothingas the model for all empty calls toController.View - Add a method to
TestSetUpwhich clears the model
Make sure that you are creating a new instance of your SUT (Subject Under Test) for each unit test. In NUnit that would be done inside a method decorated with the
[Setup]attribute:Don’t use any static fields.
MockControllershould be a private instance field of your test fixture class.