Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing "unit testable" code?

What kind of practices do you use to make your code more unit testing friendly?

like image 599
TWA Avatar asked Jun 17 '09 14:06

TWA


People also ask

How do you code a unit testable?

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.

What does it mean to write testable code?

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.

What is unit tested code?

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.


1 Answers

  • 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

like image 142
tvanfosson Avatar answered Oct 04 '22 11:10

tvanfosson