3

I need to test this method with JUnit and Mockito

 function uploadData() {
    myObject.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    upload(arguments, callbackContext);
                }
            });
        }

How to mock myObject to call upload(arguments, callbackContext) not in background thread ?

Jim
  • 8,874
  • 16
  • 68
  • 125
  • If you were to mock `myObject` to call `upload` in the current thread, not a new one, as you have asked; then you wouldn't be testing this method at all - you would have mocked away the very thing that you've set out to test. – Dawood ibn Kareem Aug 06 '13 at 20:02

2 Answers2

2

You'll need to do a few things here. First, replace the ThreadPool with a mock, so you have access to mock execute at all. Then use an ArgumentCaptor in a verify call to get access to the Runnable. Finally, trigger the Runnable and test the state afterwards.

@Test public void shouldUploadInBackground() {
  // declare local variables
  MyObject mockMyObject = Mockito.mock(MyObject.class);
  ThreadPool mockThreadPool = Mockito.mock(ThreadPool.class);
  ArgumentCaptor<Runnable> runnableCaptor =
      ArgumentCaptor.forClass(Runnable.class);

  // create the system under test
  when(mockMyObject.getThreadPool()).thenReturn(mockThreadPool);
  SystemUnderTest yourSystemUnderTest = createSystem(mockThreadPool);

  // run the method under test
  yourSystemUnderTest.uploadData();

  // set the runnableCaptor to hold your callback
  verify(mockThreadPool).execute(runnableCaptor.capture());

  // here you can test state BEFORE the callback executes
  assertFalse(yourSystemUnderTest.isDataUploaded());

  // call run on the callback
  runnableCaptor.getValue().run();

  // here you can test state AFTER the callback executes
  assertTrue(yourSystemUnderTest.isDataUploaded());
}
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
0

I think the following would work:

Mockito.doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        upload(arguments, callbackContext);
    }).when(myObjectSpy.getThreadPool()).execute(Mockito.any(Runnable.class));

but i am not realy sure.

Mihai
  • 11