jeudi 3 décembre 2015

Mockito: stub function is not working

I am using Mockito to write a simple unit test.

Then, a function under test:

public class MyService {
  public void getData() {
     executor.execute(new MyRunnable() {
        @Override
        doTask() {
          MyRestClient client = getRestClient();
          Response resp = client.getFromServer();
          persist(resp.getData());
        }
     });
  }
}

protected MyRestClient getRestClient() {
    return new MyRestClient();
}

My test case, I want to test doTask() has run & resp.getData() is persisted:

@Test
public void testGetData() {
   MyService spyService = spy(MyService.getInstance());

   // mock client
   MyRestClient mockedClient = mock(MyRestClient.class);
   mockedClient.setData("testData");

   // stub getRestClient() function to return mocked client
   when(spyService.getRestClient()).thenReturn(mockedClient);

   // SUT
   spyService.getData();

   // run the Runnable task.
   Mockito.doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Exception {
            Object[] args = invocation.getArguments();
            Runnable runnable = (Runnable) args[0];
            runnable.doTask();
            return null;
        }
    }).when(executor).execute(Mockito.any(Runnable.class));
    ...
}

As you see above, I stub the getRestClient() function to return a mocked MyRestClient. However when run the test case, it doesn't stub the getRestClient() but run the real function. Why?

Aucun commentaire:

Enregistrer un commentaire