As I have mentioned before, my company has recently started to use the Test Driven Development style of programming. In order to help us write testable code, I came up with this simple list of best practices for making our C# code base more testable. (Some of the links refer to limitations of Rhino Mocks, a mocking framework for C#, but the rules apply more generally as well.)
To maximize the testability of code, follow these rules:
To maximize the testability of code, follow these rules:
- Write the test first, then the code. (PRIME DIRECTIVE!)
Reason: This ensures that you write testable code and that every line of code gets tests written for it. - Design classes using dependency injection.See: Intro to Rhino Mocks (see "Creating Testable Web Applications" section) and Dependency Injection Article
Reason: You cannot mock or test what cannot be seen. - Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter.Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized.
- Do not write static methods or classes.See: Intro to Rhino Mocks (see "Creating Testable Web Applications" section) and Rhino Mocks Limitations
Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them. - Program off interfaces, not classes.Reason: Interfaces can be easily mocked using Rhino Mocks and other mocking frameworks.
- Isolate external dependencies.
Reason: Unresolved external dependencies. - Mark as virtual the methods you intend to mock.
See: Rhino Mocks Limitations
Reason: Rhino Mocks is unable to mock non-virtual methods.