使用 Mockito 和 JUnit 5 模拟带有参数的静态 void 方法[重复]

问题描述 投票:0回答:1

我正在尝试模拟一个带有参数的静态 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);
}

但它甚至没有编译,因为

MockedStatic 类型中的 when(MockedStatic.Verification) 方法不适用于参数 (( msg) -> {})

但我不明白为什么。

java static mocking mockito junit5
1个回答
1
投票

好的,它适用于:

  @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));
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.