首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Mockito测试Mosby

用Mockito测试Mosby
EN

Stack Overflow用户
提问于 2017-04-22 08:13:34
回答 2查看 128关注 0票数 0

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

代码语言:javascript
复制
public class DetailsPresenter extends MvpBasePresenter<DetailsView> {

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

}

我试图通过嘲弄主持人来解决这个问题:

代码语言:javascript
复制
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());
}

}

但我有个错误

代码语言:javascript
复制
    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.

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-04-22 09:00:54

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

代码语言:javascript
复制
@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");
}
票数 3
EN

Stack Overflow用户

发布于 2017-04-22 08:49:34

你有没有尝试添加一些日志记录来找出发生了什么事?

我认为你并没有找到真正的方法

代码语言:javascript
复制
mockPresenter.showCountry(any(Country.class));

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

代码语言:javascript
复制
doCallRealMethod().when(mockPresenter).showCountry(any(Country.class));

没有得到满足。如果你用一个不那么严格的条件

代码语言:javascript
复制
doCallRealMethod().when(mockPresenter).showCountry(any());

你应该得到一个NullPointerException

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43556897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档