0

I am writing unit tests for my service PlanGenerator. I have mocked necessary services and I have InjectMocked plangenerator service as follows:

@Mock
private LoggerFactory lf;

@Mock
private Logger logger;

@Mock
private RequestGenerator requestGenerator;

@InjectMocks
private PlanGenerator planGenerator;

In methods, I am able to call when method on Mocked services like requestGenerator as this:

Mockito.when(requestGenerator.getLatestRequest()).thenReturn(latestRequestDummy);

However, I am not able to call the same method on planGenerator service like this:

Mockito.when(planGenerator.someOtherMethod()).thenReturn(someValue);

It gives me MissingMethodInvocationException error while saying when() requires an argument which has to be 'a method call on a mock'

How can I mock planGenerator service, also it works as same as injectmocks?

Sami
  • 490
  • 6
  • 29
  • 1
    `planGenerator` is not a mock it cannot be used in a `when` or anywhere else you might use a mock. You annotated it `@InjectMocks` which means it's a real `PlanGenerator` with mocks such as `RequestGenerator` as a dependency. If you treat it as a mock you will not be testing your real code. If you need to use it as both a mock and a real class you should look into [Spy](https://stackoverflow.com/questions/15052984/what-is-the-difference-between-mocking-and-spying-when-using-mockito), but most people feel using a `Spy` means you have a bad design. – DCTID Feb 07 '20 at 14:41
  • How to avoid using Spy in my case? Somehow I need the information from getLatestPlan method. I can give it as parameter to the function. But in that case signature would change and in the client side, I just give that parameter as null. It is useles. – Sami Feb 17 '20 at 13:02

0 Answers0