JustADude
JustADude

Reputation: 81

Mockito - Calling real methods during When - ThenReturn clause

Consider the following class (using CDI + a cutstom Restclient)

public class A {

 @Inject
 Restclient client;

 public Object init(String token) {
    String b = createB(token);
    return c(b);
 }

 public String createB(String token)
    return client.getB(token);
 }

 public Object c(String b) {
   return new C(b);
 }
}

I want to mock the method createB(token), as I don't want to test the Rest Client. So I've done the following:

public class TestA {

     @Mock
     A a;

     @Test
     public void testA() {
          when (a.createB("123")).thenReturn("FakeB");

          Object c = a.init("123");
         assertNotNull(c); // Fails
     }
}

For some reason this JUnit 4 + Mockito 2.18 test fails as 'c' is null but my methods are correctly working (have tested them).

If I use @Spy for A, I get a NPE because my Restclient is not initialized (even if I add @Mock RestClient client) and the when(...).thenReturn(...) actually calls the real method...

No clue how to fix this even if it feels so simple...

Upvotes: 0

Views: 1587

Answers (2)

Fritz Duchardt
Fritz Duchardt

Reputation: 11870

If you want to avoid method invocations during stubbing, please use the following notation:

doXxx(...).when(spyObject).method();

So, in your case this will work:

public void test_a() {
  ...

  doReturn("FakeB").when(restClient).getB("token"));
  assertNotNull(a.init("token"))
}

Upvotes: 4

LppEdd
LppEdd

Reputation: 21124

Use @Mock in combination with @InjectMocks.

@RunWith(MockitoJUnitRunner.class)
public class TestA {
   @Mock
   RestClient restClient;

   @InjectMocks
   A a;

   public void test_a() {
      ...

      when(restClient.getB("token")).thenReturn("FakeB")
      assertNotNull(a.init("token"))
   }
}

However you must allow your A class to have a RestClient injected, e.g.

public class A {
   final Restclient restClient;

   @Inject
   public A(final RestClient restClient) {
      this.restClient = restClient;
   }

...

Which, to be honest, is the optimal way to deal with dependencies (and use CDI).

Upvotes: 2

Related Questions