Junit相关

  1. /**
  2. * JUnit对于每个@Test方法
  3. * 1.实例化MainTest对象,如MainTest test = new MainTest();
  4. * 2.执行@Before方法 test.serUp();
  5. * 3.执行@Test方法 test.test();
  6. * 4.执行@After方法 test.tearDown();
  7. */

TestableMock

https://github.com/alibaba/testable-mock

Mockito相关

Mockito注意事项

thenReturn会做类型检查,doReturn不会。
在使用Spy机制时,要小心使用thenReturn会有副作用,可以使用doReturn代替。

  1. // 优先使用
  2. when(user.getName()).thenReturn("John");
  3. // 必要时再用这个
  4. doReturn("John").when(user).getName();

参考资料:http://sangsoonam.github.io/2019/02/04/mockito-doreturn-vs-thenreturn.html

Mock接口

JDBCDialect为interface。

  1. @Mock
  2. JDBCDialect jdbcDialect;
  3. @InjectMocks
  4. MysqlSink mysqlSink = new MysqlSink();;
  5. @Before
  6. public void setUp () {
  7. MockitoAnnotations.initMocks(this);
  8. }
  9. @Test
  10. public void testGetOutputFormat() throws IllegalAccessException {
  11. when(user.getName()).thenReturn("John");
  12. // do something
  13. }

Mock私有成员

用的PowerMock组件。

  1. MemberModifier.field(MysqlSink.class, "dbUrl").set(mysqlSink, "foo");
  1. MemberModifier.stub(MemberMatcher.method(PrivateObject .class, "getPrivateString"))
  2. .toReturn("Power Mock");

Mock静态方法

https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito/21114773#21114773

Maven POM文件配置

  1. <properties>
  2. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  3. <junit.version>4.12</junit.version>
  4. <mockito.version>2.21.0</mockito.version>
  5. <powermock.version>2.0.4</powermock.version>
  6. </properties>
  1. <dependency>
  2. <groupId>junit</groupId>
  3. <artifactId>junit</artifactId>
  4. <version>${junit.version}</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.mockito</groupId>
  9. <artifactId>mockito-core</artifactId>
  10. <version>${mockito.version}</version>
  11. <scope>test</scope>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.powermock</groupId>
  15. <artifactId>powermock-module-junit4</artifactId>
  16. <version>${powermock.version}</version>
  17. <scope>test</scope>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.powermock</groupId>
  21. <artifactId>powermock-api-mockito2</artifactId>
  22. <version>${powermock.version}</version>
  23. <scope>test</scope>
  24. <exclusions>
  25. <exclusion>
  26. <groupId>org.mockito</groupId>
  27. <artifactId>mockito-core</artifactId>
  28. </exclusion>
  29. </exclusions>
  30. </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

参考资料

https://www.geek-share.com/detail/2631625275.html