首页 > 解决方案 > 将 @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 的教程进行操作,但仍然出现此错误,我不明白为什么。这是我试图解决这个问题的最后手段。

标签: androidmockitopowermockpowermockito

解决方案


您正在以正确的方式进行测试,只需替换

PowerMockito.when(Uri.parse(anyString())).thenReturn(otherUri);

与 Mockito 的时间

 Mockito.when(Uri.parse(anyString())).thenReturn(otherUri);

并将此文件添加https://gist.github.com/badr-ghazouan/1edbed170ce968ef0011f2721911ffc6到 test 文件夹下的资源文件夹中,mockito 将自动加载它而不做任何事情。

希望这对你有用


推荐阅读