引入依赖

mockito依赖至少是3.4.0+

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.mockito</groupId>
  4. <artifactId>mockito-core</artifactId>
  5. <version>3.8.0</version>
  6. <scope>test</scope>
  7. </dependency>
  8. <dependency>
  9. <groupId>org.mockito</groupId>
  10. <artifactId>mockito-inline</artifactId>
  11. <version>3.8.0</version>
  12. <scope>test</scope>
  13. </dependency>
  14. </dependencies>

Mock无参静态方法

  1. @Test
  2. void givenStaticMethodWithNoArgs_whenMocked_thenReturnsMockSuccessfully() {
  3. assertThat(StaticUtils.name()).isEqualTo("Baeldung");
  4. try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
  5. utilities.when(StaticUtils::name).thenReturn("Eugen");
  6. assertThat(StaticUtils.name()).isEqualTo("Eugen");
  7. }
  8. assertThat(StaticUtils.name()).isEqualTo("Baeldung");
  9. }

Mock有参静态方法

  1. @Test
  2. void givenStaticMethodWithArgs_whenMocked_thenReturnsMockSuccessfully() {
  3. assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
  4. try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
  5. utilities.when(() -> StaticUtils.range(2, 6))
  6. .thenReturn(Arrays.asList(10, 11, 12));
  7. assertThat(StaticUtils.range(2, 6)).containsExactly(10, 11, 12);
  8. }
  9. assertThat(StaticUtils.range(2, 6)).containsExactly(2, 3, 4, 5);
  10. }