我正在尝试使用Mockito模拟数据并获得NPE。这是我要测试的示例代码:
public class MyPresenter implements Contract.Presenter {
@Inject
MyManager myManager;
@Override
public void doSomething(Data data) {
myManager.doSomething(data);
}
}
public class MyPresenterTest {
@Mock
private MyManager myManager;
@InjectMocks
private MyPresenter myPresenter;
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
}
@Test
public void doSomethingTest(){
Data data = new Data();
myPresenter.doSomething(data);
verify(myManager).doSomething(data);
}
}
NPE在MyPresenter类的下一行。
myManager.doSomething(data);
@Inject in MyPresenter使用Dagger 2注入对象。
任何人都可以帮忙吗?
答案 0 :(得分:2)
Mockito仅将模拟内容注入构造函数,而字段未定义。为了正确测试它,需要手动使用构造函数参数和Mockito初始化类。如果您可以添加一个接受MyManager实例的构造函数(例如-
),它将起作用。public class MyPresenter implements Contract.Presenter {
@Inject
MyManager myManager;
public MyPresenter(MyManager myManager){ // constructor is required for mocikto to inject your fields.
this.myManager = manager
}
@Override
public void doSomething(Data data) {
myManager.doSomething(data);
}
}