【问题标题】:Using Mockito but getting null pointer exception when running the test case使用 Mockito 但在运行测试用例时出现空指针异常
【发布时间】:2019-02-17 16:57:17
【问题描述】:

我正在尝试使用 selenium webelement 作为参数为函数创建测试用例。

我正在尝试模拟该元素,但这个测试用例给出了错误。我正在尝试制作测试用例的方法是这样的。

 @Override
    public boolean isDownloadStarted(WebDriver driver) {
        boolean isDownloadStarted = false;
        ArrayList<String> tabs = new ArrayList<>(driver.getWindowHandles());
        if (tabs.size() == 1) {
            isDownloadStarted = true;
        }
        return isDownloadStarted;
    }

测试用例给出空指针异常

DownloadStatusListenerImpl status;

@Before
public void before() {
    MockitoAnnotations.initMocks(this);
    status = new DownloadStatusListenerImpl();
}
@Test
    public void testDownloadStatusListenerImpl() {
        Mockito.when(status.isDownloadStarted(Mockito.any(WebDriver.class))).thenReturn(true);
        assertEquals(true, status.isDownloadStarted(Mockito.any(WebDriver.class)));
    }

【问题讨论】:

    标签: java selenium selenium-webdriver junit mockito


    【解决方案1】:

    您没有对status 存根。您可以向其添加 @Spy 注释(并停止覆盖它):

    @Spy // Annotation added here
    DownloadStatusListenerImpl status;
    
    @Before
    public void before() {
        MockitoAnnotations.initMocks(this);
        // Stopped overwriting status here
    }
    

    或者你可以显式调用Mockito.spy:

    @Before
    public void before() {
        status = Mockito.spy(new DownloadStatusListenerImpl());
    }
    

    编辑:

    在这样的方法上调用when 仍然会调用它,因此会失败。您需要改用doReturn 语法:

    Mockito.doReturn(true).when(status).isDownloadStarted(Mockito.any(WebDriver.class));
    

    【讨论】:

    • 使用 Spy 也只会给出同样的错误 NullPointerException。
    • @WhiteWalker Arg,我的 mockito-fu 没有练习了。请参阅我编辑的答案。
    • 即使按照您的建议使用 doReturn 后,也会出现相同的结果空指针异常。
    猜你喜欢
    • 2017-11-17
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-13
    相关资源
    最近更新 更多