Multiple Asserts in Unit Tests – Is it bad?

Unit test code should be treated like first class code so it should be maintained and refactored to improve its qualities just like any other production code.

In test code one smell is having multiple asserts in a test method which usually indicates that the same test method may be testing multiple scenarios. Take the following example:

        public void Divide_ShouldWorkCorrectly()
            var calculator = new Calculator();

            Assert.AreEqual(2, calculator.Divide(4, 2));
            Assert.AreEqual(4, calculator.Divide(4, 1));
            MSTestExtensions.ExceptionAssert.Throws<DivideByZeroException>(() => calculator.Divide(4, 0));

Continue reading

Unit Testing Made Easy with Custom Model Binders

In ASP.NET MVC 3, Microsoft has made unit testing controller actions quite easy. Generally you follow 3 basic steps:

  • setup your dependencies
  • call the controller action you want to test
  • assert something on the properties(usually the Model property) of the returned ActionResult derived object.

However there still is a pain point when the action under test makes use of so called ASP.NET intrinsic objects (Request, Response, Session, Cache, Server etc.) which are hold in the HttpContext instance.

Continue reading