What kind of practices do you use to make your code more unit testing friendly?
To prepare your code to be testable:Document your assumptions and exclusions. Avoid large complex classes that do more than one thing - keep the single responsibility principle in mind. When possible, use interfaces to decouple interactions and allow mock objects to be injected.
Writing testable code means that the smallest components are independently verifiable. In order to do this, each component must have its dependencies injected into it. This means that code can't reference global variables or use read/write singletons or service locators, etc.
In computer programming, unit testing is a software testing method by which individual units of source code—sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures—are tested to determine whether they are fit for use.
TDD -- write the tests first, forces you to think about testability and helps write the code that is actually needed, not what you think you may need
Refactoring to interfaces -- makes mocking easier
Public methods virtual if not using interfaces -- makes mocking easier
Dependency injection -- makes mocking easier
Smaller, more targeted methods -- tests are more focused, easier to write
Avoidance of static classes
Avoid singletons, except where necessary
Avoid sealed classes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With