what is unit test?
单元测试中的单元是一个系统或一个程序的组成部分,单元测试就是要对这些组成部分进行独立地、隔离地以某种约束和规则进行的测试,以发现每一部分的问题或者确定该部分不存在问题。Essentially, a unit test is a method that instantiates a small portion of our application and verifies its behavior independently from other parts. A typical unit test contains 3 phases: First, it initializes a small piece of an application it wants to test (also known as the system under test, or SUT), then it applies some stimulus to the system under test (usually by calling a method on it), and finally, it observes the resulting behavior. If the observed behavior is consistent with the expectations, the unit test passes, otherwise, it fails, indicating that there is a problem somewhere in the system under test.
也即,单元测试实例化系统的一小部分,然后相对独立地确定此部分的行为是否正确。
why unit test?
The goal of Android unit test is to isolate each part of the program and show that the individual parts are correct. A unit test provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.—Wikipedia
将系统的不同模块分离进行测试,有利于不同team和不同团队成员协作,不同team可以独立地完成各自的任务,而不用相互block,对于同一team的不同成员也同样适用。
test theory
- 系统要分层或者分模块
不同的Part可能有不同的特征,应采用不同的测试工具和测试方法 - 最小化原则
如果一个测试没有pass的原因有多种,涉及的系统模块不止一个,那么这个测试不符合最小化原则,不能用于快速地发现问题。 - 系统的各模块之间要解耦
如果系统各模块之间的耦合过于严重,在实例化预测试Part时,需要Mock多个其他Part的组件,增加了
- 系统要分层或者分模块