我正在使用Mockito来测试我的ViewModel,但是IM使用ContextCompat
获得NullPointerException
。
@RunWith(MockitoJUnitRunner.class)
public class ViewModelUnitTest {
@Mock
private MockContext mockContext;
private ViewModel pViewModel;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCProfile() throws Exception {
Profile cProfile = GeneratorAPI.getCProfile();
pViewModel = new ViewModel(cProfile, mockContext);
assertEquals(View.GONE, pViewModel.userVisibilty.get());
}
}
}
//ViewModel
public ViewModel(Profile profile, Context context) {
this.profile = profile;
this.context = context;
this.userTitleColor = new ObservableInt(ContextCompat.getColor(context, R.color.black));
this.userVisibilty = new ObservableField<>();
}
但是,我会使用ContextCompat
遇到以下错误:
java.lang.NullPointerException
at android.support.v4.content.ContextCompat.getColor(ContextCompat.java:411)
at ...ViewModel.<init>(ViewModel.java:102)
at ....ViewModelUnitTest. testCProfile(ViewModelUnitTest.java:60)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at ..
预先感谢
当我面对这个问题时,我所做的。修改了您的测试文件如下。
@RunWith(MockitoJUnitRunner.class)
public class ViewModelUnitTest {
@Mock
private MockContext mockContext;
private ViewModel pViewModel;
private Resources mockResources;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
when(mockContext.getResources()).thenReturn(mockResources)
when(mockResources.getColor(anyInt(), any())).thenReturn(anyInt())
}
@Test
public void testCProfile() throws Exception {
Profile cProfile = GeneratorAPI.getCProfile();
pViewModel = new ViewModel(cProfile, mockContext);
assertEquals(View.GONE, pViewModel.userVisibilty.get());
}
}
}
说明:ContextCompat.getColor()
API调用适当的Context
API获取颜色ID。因此,我们必须嘲笑这些API调用以避免NPE。