ContextCompat与Mockito NullPointerException

时间:2018-03-01 07:38:04

标签: android mvvm mockito

我正在使用mockito对我的viewmodel进行单元测试,但我正在使用NullPointerException获取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());
       }
    }
}

//视图模型

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 ..

提前致谢

1 个答案:

答案 0 :(得分:0)

这是我在面对这个问题时所做的。 修改了您的测试文件,如下所示。

    @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。