Writing “unit testable” code?

2019-01-16 04:02发布

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

19条回答
Fickle 薄情
2楼-- · 2019-01-16 04:33

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.

查看更多
疯言疯语
3楼-- · 2019-01-16 04:33

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.
  • When possible, make pubic method virtual to allow mock objects to emulate them.
  • When possible, use composition rather than inheritance in your designs - this also encourages (and supports) encapsulation of behaviors into interfaces.
  • When possible, use dependency injection libraries (or DI practices) to provide instances with their external dependencies.

To get the most out of your unit tests, consider the following:

  • Educate yourself and your development team about the capabilities of the unit testing framework, mocking libraries, and testing tools you intend to use. Understanding what they can and cannot do will be essential when you actually begin writing your tests.
  • Plan out your tests before you begin writing them. Identify the edge cases, constraints, preconditions, postconditions, and exclusions that you want to include in your tests.
  • Fix broken tests as near to when you discover them as possible. Tests help you uncover defects and potential problems in your code. If your tests are broken, you open the door to having to fix more things later.
  • If you follow a code review process in your team, code review your unit tests as well. Unit tests are as much a part of your system as any other code - reviews help to identify weaknesses in the tests just as they would for system code.
查看更多
孤傲高冷的网名
5楼-- · 2019-01-16 04:37

You don't necessarily need to "make your code more unit testing friendly".

Instead, a mocking toolkit can be used to make testability concerns go away. One such toolkit is JMockit.

查看更多
SAY GOODBYE
6楼-- · 2019-01-16 04:38

Dependency injection seems to help.

查看更多
在下西门庆
7楼-- · 2019-01-16 04:38

I use Test-Driven Development whenever possible, so I don't have any code that cannot be unit tested. It wouldn't exist unless the unit test existed first.

查看更多
登录 后发表回答