Search code examples
javaspring-bootunit-testingjunit5mockstatic

Mock LocalDateTime gives org.mockito.exceptions.misusing.MissingMethodInvocationException - Springboot Unit test writing


I need to mock LocalDateTime without using power mockito. But it gives be below error with a exception.

when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
//////////////
org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.
org.mockito.exceptions.misusing.MissingMethodInvocationException: 
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);
Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

This is the code so far.

@EnableAutoConfiguration
@SpringBootTest
public class StudentC10IT {

  @Autowired
  ClassA classA;
  
  @Test
  @Tag("VerifyProcess")
  @DisplayName("Verify kafka event consumer from configuration manager")
  void verifyProcess(){
    try (MockedStatic<LocalDateTime> localDateTimeMockedFourMonth = Mockito
            .mockStatic(LocalDateTime.class, Mockito.CALLS_REAL_METHODS)) {
      localDateTimeMockedFourMonth.when(LocalDateTime::now).thenReturn(LocalDateTime.of(2017, 8, 24, 8, 50, 9));
      classA.processStudentFile();
    }
  }

}

I want to know how to mock LocalDateTime without using power mockito ?


Solution

  • The parameter in your .thenReturn statement attempts to use a static method of the class which you are currently mocking. Move LocalDateTime.of(...) outside of your try-block, and it seems to execute correctly.