android - 将 @RunWith(PowerMockrunner.class) 添加到测试中会提供所有其他测试 NPE
问题描述
我有一个测试类,我在其中运行 Mockito 测试,例如:
public class ViewModelTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
@Test
public void openQuestion() {
viewModel.openQuestion(context, QUESTION_ID);
verify(questionRouter).open(context, QUESTION_ID); //just an example
}
}
一切正常。但是,我必须在我的一个测试类中模拟一个静态方法,所以我将 PowerMock 添加到我的类中:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Uri.class)
public class ViewModelTest { ...
和依赖项:
testImplementation 'org.powermock:powermock-core:2.0.2'
testImplementation 'org.powermock:powermock-api-mockito2:2.0.2'
testImplementation 'org.powermock:powermock-module-junit4-rule-agent:2.0.2'
testImplementation 'org.powermock:powermock-module-junit4-rule:2.0.2'
testImplementation 'org.powermock:powermock-module-junit4:2.0.2'
但是当我现在尝试运行测试时(假设我有 15 种测试方法),我在大多数测试方法上都得到了 NPE:
java.lang.NullPointerException
at com.example.Viewmodel.prepare(StartViewModel.java:126)
即使在我尝试模拟静态方法的方法中,我也会得到 NPE:
PowerMockito.mockStatic(Uri.class);
PowerMockito.when(Uri.parse(anyString())).thenReturn(otherUri);
在您投票关闭 NPE 之前,我确实查看了 SO 和其他站点中的大多数答案,尝试了其中的许多,但没有一个对我有用。我按照 Powermock 的教程进行操作,但仍然出现此错误,我不明白为什么。这是我试图解决这个问题的最后手段。
解决方案
您正在以正确的方式进行测试,只需替换
PowerMockito.when(Uri.parse(anyString())).thenReturn(otherUri);
与 Mockito 的时间
Mockito.when(Uri.parse(anyString())).thenReturn(otherUri);
并将此文件添加https://gist.github.com/badr-ghazouan/1edbed170ce968ef0011f2721911ffc6
到 test 文件夹下的资源文件夹中,mockito 将自动加载它而不做任何事情。
希望这对你有用
推荐阅读
- java - 升级到 macOS Big Sur 后无法启动 Neo4j 控制台应用程序
- python - Python - 计算两个不同列中相同值的出现次数
- sql - 如何插入 table1 列,其中另一个 table1 列与 table2 列相同
- python - 如何用python估计硬币翻转的概率?
- c++ - 当我们尝试获取 NULL 字符串的长度时,为什么会出现运行时错误?
- ruby - 找出一天中注册人数最多的时间
- react-native - 当 Text 组件被另一个 Text 组件包裹时,ellipsizeMode 不起作用
- vulkan - 更新加速结构时的验证错误(VK_KHR_ray_tracing)
- java - Gradle 和 API 依赖
- javascript - 如何在 svelte 的 javascript 中单击按钮时调用异步函数?