javaspring-bootunit-testingmockito

not able to mock functional interface when testing controller and functional interface is being called from controller


SomeClass instance = someService.getSomething.apply("by-something");

above statement is being used in controller to fetch data. I want to test controller. So i am mocking above line in test as below.

@Mock
private SomeService someService;

@Mock
private Function<String, SomeTrigger> someTriggerFunction;


when(someService.getSomething.apply("by-something")).thenReturn(someTrigger);

Now it giving me below error

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/native/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.

Solution

  • You should set the getSomething field in someService like this :

    @Mock
    private SomeService someService;
    
    @Mock 
    private Function<String, SomeTrigger> someTriggerFunction;
    
    ...
    
    someService.getSomething = someTriggerFunction;
    
    when(someTriggerFunction.apply("by-something")).thenReturn(someTrigger);