【问题标题】:Testing Mosby with Mockito用 Mockito 测试 Mosby
【发布时间】:2017-04-22 08:13:34
【问题描述】:

我正在使用 Mosby,我想测试我的简单演示器。

public class DetailsPresenter extends MvpBasePresenter<DetailsView> {

public void showCountry(Country country) {
    getView().setTitle(country.getName());
    getView().setFlag(country.getFlagUrl());
}

}

我试图通过模拟 Presenter 来解决它:

public class DetailsPresenterTest {

private DetailsPresenter mockPresenter;
private DetailsView mockView;

@Before
public void setUp() throws Exception {
    mockPresenter = mock(DetailsPresenter.class);
    mockView = mock(DetailsView.class);

    when(mockPresenter.isViewAttached()).thenReturn(true);
    when(mockPresenter.getView()).thenReturn(mockView);

    doCallRealMethod().when(mockPresenter).showCountry(any(Country.class));
}

@Test
public void shouldShowFlag() throws Exception {
    mockPresenter.showCountry(any(Country.class));
    verify(mockView, times(1)).setFlag(anyString());
}

@Test
public void shouldShowName() throws Exception {
    mockPresenter.showCountry(any(Country.class));
    verify(mockView, times(1)).setTitle(anyString());
}

}

但我有错误

    Wanted but not invoked:
detailsView.setFlag(<any string>);
-> at eu.szwiec.countries.details.DetailsPresenterTest.shouldShowFlag(DetailsPresenterTest.java:39)
Actually, there were zero interactions with this mock.

我也尝试过使用真正的演示者,但没有成功。

【问题讨论】:

    标签: unit-testing mockito tdd mosby


    【解决方案1】:

    您必须使用真实的 Presenter 和真实的国家对象来调用 showCountry()。其他一切都没有意义(不是测试真正的演示者,而是模拟演示者实例)。

    @Test
    public void showFlagAndName(){
       DetailsView mockView = mock(DetailsView.class);
       DetailsPresenter presenter = new DetailsPresenter();
       Country country = new Country("Italy", "italyFlag");
    
       presenter.attachView(mockView);
    
       presenter.showCountry(country);
    
       verify(mockView, times(1)).showCountry("Italy");
       verify(mockView, times(1)).setFlag("italyFlag");
    }
    

    【讨论】:

    • 从技术上讲,他不需要一个完整的演示者。可以将被测行为简化为一种方法,但从战略的角度来看,他确实应该测试整个事物。
    • 太好了,感谢您的完美回答!我对 Country 对象有疑问。在这种情况下我也可以使用它的模拟吗?或者这是一种不好的做法?
    • 任何对你有用的东西。您测试的真实课程越多越好。否则,您最终会针对模拟编写测试,因此您实际上是在测试模拟而不是真实的类。 IE。模拟(使用 mockito)没有内部状态,而您的真实类可能在您的方法主体中有状态和 if 分支。
    【解决方案2】:

    您是否尝试添加一些日志记录以了解发生了什么?

    我觉得你打的不是真正的方法

    mockPresenter.showCountry(any(Country.class));
    

    不构造Country 对象实例,而只是传递null。所以条件

    doCallRealMethod().when(mockPresenter).showCountry(any(Country.class));
    

    不满足。如果您使用不太严格的条件

    doCallRealMethod().when(mockPresenter).showCountry(any());
    

    你应该得到一个NullPointerException

    您可以通过在方法调用中使用真实或模拟的 Country 实例来解决此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-06
      • 1970-01-01
      • 2012-09-12
      • 1970-01-01
      相关资源
      最近更新 更多