mW3
mW3

Reputation: 189

mockito unit testing Wanted but not invoked:

I have seen there are similar question already exist in SO , I tried all the solution , but couldn't fix my problem , as I am new to tdd

I have a class like this

public class AppUpdatesPresenter  {

    public void stopService() {
        ServiceManager.on().stopService();
    }
}

I have the test class like this

@RunWith(MockitoJUnitRunner.class)
public class AppUpdatesPresenterTest {
       @Mock
       AppUpdatesPresenter appUpdatesPresenter;

       @Mock
       ServiceManager serviceManager;

       @Mock
       Context context;

       @Test
       public void test_Stop_Service() throws Exception {
            appUpdatesPresenter.stopService();
            verify(serviceManager,times(1)).stopService();
       }

}

When I tried to test that , if I call stopService() method , then ServiceManager.on().stopService(); called at least once .

But I am getting the following error

Wanted but not invoked:
serviceManager.stopService();
-> at io.example.myapp.ui.app_updates.AppUpdatesPresenterTest.test_Stop_Service(AppUpdatesPresenterTest.java:103)
Actually, there were zero interactions with this mock.

Not sure whats gone wrong .

Upvotes: 2

Views: 2500

Answers (1)

jaychang0917
jaychang0917

Reputation: 1888

When you call appUpdatesPresenter.stopService();, nothing happened as you didn't tell it what should be happened.

To make your test pass, you need stubbing the appUpdatesPresenter.

@Test
public void test_Stop_Service() throws Exception {
    doAnswer { serviceManager.stopService(); }.when(appUpdatesPresenter).stopService()
    appUpdatesPresenter.stopService();
    verify(serviceManager).stopService();
}

Btw, the above test is meaningless as you stub all the things.


To make the test case meaningful, you should inject the ServiceManager instead of coupling it with AppUpdatePresenter.

public class AppUpdatesPresenter  {
    private final ServiceManager serviceManager;

    public AppUpdatesPresenter(ServiceManager serviceManager) {
        this.serviceManager = serviceManager;
    }

    public void stopService() {
        sm.stopService();
    }
}

Then make the AppUpdatesPresenter under test.

@InjectMock AppUpdatesPresenter appUpdatesPresenter;

Now the test case doesn't rely on canned interaction but real implementation of your code.

@Test
public void test_Stop_Service() throws Exception {
    appUpdatesPresenter.stopService();
    verify(serviceManager).stopService();
}

Upvotes: 1

Related Questions