Junit相关
/**
* JUnit对于每个@Test方法
* 1.实例化MainTest对象,如MainTest test = new MainTest();
* 2.执行@Before方法 test.serUp();
* 3.执行@Test方法 test.test();
* 4.执行@After方法 test.tearDown();
*/
TestableMock
https://github.com/alibaba/testable-mock
Mockito相关
Mockito注意事项
thenReturn会做类型检查,doReturn不会。
在使用Spy机制时,要小心使用thenReturn会有副作用,可以使用doReturn代替。
// 优先使用
when(user.getName()).thenReturn("John");
// 必要时再用这个
doReturn("John").when(user).getName();
参考资料:http://sangsoonam.github.io/2019/02/04/mockito-doreturn-vs-thenreturn.html
Mock接口
JDBCDialect为interface。
@Mock
JDBCDialect jdbcDialect;
@InjectMocks
MysqlSink mysqlSink = new MysqlSink();;
@Before
public void setUp () {
MockitoAnnotations.initMocks(this);
}
@Test
public void testGetOutputFormat() throws IllegalAccessException {
when(user.getName()).thenReturn("John");
// do something
}
Mock私有成员
用的PowerMock组件。
MemberModifier.field(MysqlSink.class, "dbUrl").set(mysqlSink, "foo");
MemberModifier.stub(MemberMatcher.method(PrivateObject .class, "getPrivateString"))
.toReturn("Power Mock");
Mock静态方法
https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito/21114773#21114773
Maven POM文件配置
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.12</junit.version>
<mockito.version>2.21.0</mockito.version>
<powermock.version>2.0.4</powermock.version>
</properties>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
</exclusion>
</exclusions>
</dependency>
Rule
https://skyao.io/learning-java-unit-test/junit/base/rule/TestWatcher.html
注意问题
跨 Maven Module的test目录(src/test/java)之间的Java类不能相互引用。Maven会保证它们之间的独立性禁止引用。
构造函数不要写业务逻辑:
构造函数有业务逻辑导致单元测试很麻烦,由于Mock失败
Jacoco和PowerMock冲突问题
https://stackoverflow.com/questions/23983740/unable-to-get-jacoco-to-work-with-powermockito-using-offline-instrumentation