Search code examples
javastaticmockingmockitojunit5

Mock static void method with parameters using Mockito and JUnit 5


I am trying to mock a static void method that takes a parameter, SMTPTools.send(Message)

My deps:

<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>

I tried:

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

But it's not even compiling, because

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

But I don't understand why.


Solution

  • Ok it works with:

      @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));
        }
      }