0

我正在使用 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.

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

4

2 回答 2

3

你必须使用真正的 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");
}
于 2017-04-22T09:00:54.133 回答
1

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

我认为你没有击中真正的方法

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

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

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

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

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

你应该得到一个NullPointerException.

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

于 2017-04-22T08:49:34.127 回答