【发布时间】:2019-06-07 16:26:55
【问题描述】:
我有一个运行 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 的教程进行操作,但仍然出现此错误,我不明白为什么。这是我试图解决这个问题的最后手段。
【问题讨论】:
标签: android mockito powermock powermockito