我试图用摩擦图模拟数据并获得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);
mypresenter中的@inject使用dagger2。
任何人都可以帮忙吗?
Mockito仅向构造函数模拟oft offitor,使字段不确定。为了正确测试它,需要手动用构造函数参数和摩索通o来初始化类。如果您可以添加一个构造函数,该构造函数会添加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);
}
}