Petr Shypila
Petr Shypila

Reputation: 1509

Mockito. Mock single method which throws an exception

I have a class with method impersonate which throws UnsupportedOperationException. So I want to mock only this only method. I know that I can do it with Mockito.spy.

Session session = Mockito.spy(new Session("admin", "adminSpace"));
Session imperSession = new Session("test", "testSpace");
when(session.impersonate(any(Credentials.class))).thenReturn(imperSession);

But the problem is that Mockito really calls impersonate and UnsupportedOperationException throws the execution. So what can I do here?

Upvotes: 0

Views: 685

Answers (1)

BetaRide
BetaRide

Reputation: 16884

If you have to make sure mockito is not calling your method befor it's mocked you have to use the Mockito.doXXX() methods instead of Mockito.when().

In your case the code should look like:

doReturn(imperSession).when(session).impersonate(any(Credentials.class));

Upvotes: 3

Related Questions