Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContextCompat with Mockito NullPointerException

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

like image 273
user3133966 Avatar asked Feb 10 '26 05:02

user3133966


1 Answers

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.

like image 189
karthikk Avatar answered Feb 16 '26 06:02

karthikk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!