使用 mockito 和 Junit5 模拟带参数的 static void 方法

Mock static void method with params using mockito and Junit5

我正在尝试模拟一个带参数的静态 void 方法 SMTPTools.send(Message)

我的部门:

    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter-engine</artifactId>
      <version>5.7.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-core</artifactId>
      <version>3.6.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-inline</artifactId>
      <version>3.6.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-junit-jupiter</artifactId>
      <version>3.6.0</version>
      <scope>test</scope>
    </dependency>

试一试:

    try (MockedStatic<SMTPTools> smtpToolsMocked = Mockito.mockStatic(SMTPTools.class)) {
      smtpToolsMocked.when((msg) -> SMTPTools.send(msg)).thenAnswer((Answer<Void>) invocation -> null);
    }

但它甚至没有编译原因

The method when(MockedStatic.Verification) in the type MockedStatic is not applicable for the arguments (( msg) -> {})

但我明白为什么

好的,它适用于:

  @Test
  public void staticTest() throws Exception {
    try (MockedStatic<SMTPTools> smtpToolsMocked = Mockito.mockStatic(SMTPTools.class)) {
      Message msg = null;
      smtpToolsMocked.when((msg) -> SMTPTools.send(msg)).thenAnswer((Answer<Void>) invocation -> null);
      SMTPTools.send(msg);
      smtpToolsMocked.verify(Mockito.times(1), () -> SMTPTools.send(msg));
    }
  }