我有一个演示者,它有一个返回视图的方法getView()。实现MyView(接口)的视图有一个方法isActive,它指示它是否处于活动状态。
我正在测试演示者。
在testClass的@Before设置中,我初始化了演示者。
testClass.java:
@RunWith(AndroidJUnit4.class)
public class testClass {
private Presenter presenter;
@Mock
private MyView mockView;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
presenter = new Presenter(mockView);
when(mockView.isActive()).thenReturn(true);
}
@Test
public void testIsActive() {
presenter.isViewActive();
verify(mockView).isActive();
}
Presenter.java:
public class Presenter {
private MyView view;
// The following view is an instance of MyView, not View (typo before).
public Presenter(MyView view) {
this.view = view;
}
public boolean isViewActive() {
return getView().isActive();
}
public MyView getView() {
return view;
}
}
MyView.class:
public interface MyView {
boolean isActive();
}
但是,上面的代码会在
时生成NullPointerExceptionpresenter.isViewActive();
正在运行。
为什么?
当我更换
@Mock
private MyView mockView;
与
@Mock
private ConcreteMyView mockView;
其中ConcreteMyView是MyView接口的实现,代码运行顺畅。
任何提示?
答案 0 :(得分:0)
我mdewit已经确定您的测试类正在使用View(未显示/已定义)而不是MyView。
如果您遇到问题,可以查看以下代码并进行比较。
public class SomeTest {
private Presenter presenter;
@Mock
private MyView mockView;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
presenter = new Presenter(mockView);
when(mockView.isActive()).thenReturn(true);
}
@Test
public void testIsActive() {
assertTrue(presenter.isViewActive());
verify(mockView).isActive();
}
private class Presenter {
private MyView view;
public Presenter(MyView view) {
this.view = view;
}
public boolean isViewActive() {
return getView().isActive();
//return true;
}
public MyView getView() {
return view;
}
}
private interface MyView {
boolean isActive();
}
}