問題描述
編寫“單元測試”代碼? (Writing "unit testable" code?)
What kind of practices do you use to make your code more unit testing friendly?
參考解法
方法 1:
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
方法 2:
Dependency injection seems to help.
方法 3:
Write the tests first - that way, the tests drive your design.
方法 4:
- Use TDD
- When writing you code, utilise dependency injection wherever possible
- Program to interfaces, not concrete classes, so you can substitute mock implementations.
方法 5:
Make sure all of your classes follow the Single Responsibility Principle. Single responsibility means that each class should have one and only one responsibility. That makes unit testing much easier.
(by TWA、tvanfosson、dss539、Shane Fulmer、PaulJWilliams、Robert Cartaino)