I think that anyone can agree that good code is S.O.L.I.D. code, and Dependency Inversion Principle (DIP) is a very important one.
The principle states that:
A. High-level modules should not depend on low-level modules. Both should depend
B. Abstractions should not depend upon details. Details should depend upon
DIP is very useful when you want to isolate a more abstract type from it’s dependencies (details) by usage of interfaces which receive a concrete type via Dependency Injection pattern. So instead of having a direct dependency like this…
…you put an interface between the two components like this:
Noting too special until now but what about the physical location of the interface?
Switching from “normal” coding techniques to TDD can be difficult but once you were able to make the mental switch you realize that there is more substance to TDD than just the usual hype phrase “red, green, refactor”.
Test Driven Development can be approached from a various set of angles (some of which probably I don’t even know…yet). Martin Fowler divided TDD practitioners in two categories classics and mockists (details here). Coming from a background where unit testing heavily relied on mocks for perfect isolation of the tests I consider myself to be a mockist TDDer.
While doing TDD you can practically start anywhere in the system from any component/class you like (assuming here that a basic design is already created, and you have a rough view of the system), however the way you go about it, top-down, bottom-up or from the middle has its peculiarities.
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));
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.