I am using mockito to unit test my viewmodel, however im getting a NullPointerException with ContextCompat.
@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<>();
}
However Im getting the following error with the 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 ..
Thanks in advance
This what I did when I face this issue. Modified your test file as follows.
@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());
}
}
Explanation: ContextCompat.getColor() API call appropriate Context API to get the color id. So we have to mock those API calls to avoid the NPE.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With