gpt4 book ai didi

android - ContextCompat与Mockito NullPointerException

转载 作者:行者123 更新时间:2023-12-03 10:15:42 25 4
gpt4 key购买 nike

我正在使用Mockito对我的 View 模型进行单元测试,但是我使用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());
}
}
}

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

关于android - ContextCompat与Mockito NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49044783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com