0

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.
1
  • 1
    There's never a good reason to mock a functional interface. Just use a real one that returns the desired result. Commented Dec 18, 2024 at 20:11

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

can not pass someTriggerFunction in constructor, it has already couple of params but not functional interface in constructor, there is method someTriggerFunction which has return type as Function and in order to call that i am calling it from controller, but not able to mock, i have tried below as well when(someService.getSomething).thenReturn(someTriggerFunction); when(someTriggerFunction.apply(someSource)).thenReturn(someTrigger);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.