Junit 需要mockito单元测试,但未调用:

Junit 需要mockito单元测试,但未调用:,junit,mockito,tdd,Junit,Mockito,Tdd,我看到在中已经存在类似的问题,所以我尝试了所有的解决方案,但无法解决我的问题,因为我是tdd 我有一节这样的课 public class AppUpdatesPresenter { public void stopService() { ServiceManager.on().stopService(); } } 我有这样的测试课 @RunWith(MockitoJUnitRunner.class) public class AppUpdatesPresen

我看到在中已经存在类似的问题,所以我尝试了所有的解决方案,但无法解决我的问题,因为我是
tdd

我有一节这样的课

public class AppUpdatesPresenter  {

    public void stopService() {
        ServiceManager.on().stopService();
    }
}
我有这样的测试课

@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();
       }

}
当我尝试测试时,如果我调用
stopService()
方法,那么
ServiceManager.on().stopService()至少调用一次

但是我得到了以下错误

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.

不知道出了什么问题

当您调用
AppUpdatePresenter.stopService()时,没有发生任何事情,因为您没有告诉它应该发生什么

要使测试通过,需要将
appupdatepresenter
存根

@Test
public void test_Stop_Service() throws Exception {
    doAnswer { serviceManager.stopService(); }.when(appUpdatesPresenter).stopService()
    appUpdatesPresenter.stopService();
    verify(serviceManager).stopService();
}
public class AppUpdatesPresenter  {
    private final ServiceManager serviceManager;

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

    public void stopService() {
        sm.stopService();
    }
}
顺便说一句,上面的测试毫无意义,因为你把所有的东西都存根了


为了使测试用例有意义,您应该注入
ServiceManager
,而不是将其与
AppUpdatePresenter
耦合

@Test
public void test_Stop_Service() throws Exception {
    doAnswer { serviceManager.stopService(); }.when(appUpdatesPresenter).stopService()
    appUpdatesPresenter.stopService();
    verify(serviceManager).stopService();
}
public class AppUpdatesPresenter  {
    private final ServiceManager serviceManager;

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

    public void stopService() {
        sm.stopService();
    }
}
然后对
appupdatepresenter
进行测试

@InjectMock AppUpdatesPresenter appUpdatesPresenter;
现在,测试用例不依赖于固定的交互,而是依赖于代码的真实实现

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

非常感谢您的回答,但是在我的例子中,
ServiceManager
类是单音的,在这种情况下我能做什么?