Yesterday I was writing some NUnit tests for an MVC controller. My test was making sure that a property on the model being placed in the view had a property set correctly:
1: var sut = new MyController(fakeProvider);
2: var result = (ViewResult) sut.Index(id);
3: var model = result.Model;
4: Assert.That(model.MyProperty, Is.EqualTo(expectedValue);
Often type casting can be full of syntactic noise. I could refactor that code to remove a line:
1: var sut = new MyController(fakeProvider);
2: var model = ((ViewResult) sut.Index(id)).Model;
3: Assert.That(model.MyProperty, Is.EqualTo(expectedValue);
All those parenthesis on line two are like fingernails on a chalkboard to me. Luckily I was having a problem with the razor view when I was trying to preview the controller that resulted in me hacking away at my code until it looked like:
1: var sut = new MyController(fakeProvider);
2: dynamic result = sut.Index(id);
3: Assert.That(result.Model.MyProperty, Is.EqualTo(expectedValue);
I didn’t even notice until this morning when working on another action in the controller that I had removed the need for casting my ActionResult to a ViewResult in my test. What a happy accident. I suspect that the compiler is doing the type casting for me under the covers, but I leave ILDASM to @vcsjones, so I’ll never know for sure.
I am filing that little tidbit in my bag of tricks and will definitely be using that in the future.