java - 使用Mockito但运行测试用例时出现空指针异常

标签 java selenium selenium-webdriver junit mockito

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

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

 @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)));
    }

最佳答案

您没有 stub 状态。您可以向其添加 @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));

关于java - 使用Mockito但运行测试用例时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54735478/

相关文章:

java - Java中根据monitor对象的特定属性同步线程

Java SimpleDateFormat 解析错误的日期

java - 使用反射获取 Pagefactory WebElement 名称

maven - 如何在 jenkins 中设置 chrome 浏览器窗口分辨率

python-2.7 - Selenium python : what is 'lambda' in webdriverwait. 直到语句

c# - 使用 Selenium 从表中获取数据

java - sun.net.www.protocol.https.HttpsURLConnectionImpl 无法转换为 sun.net.www.protocol.http.HttpURLConnection

java - Spring Data REST 中的事务管理

Java 动态 bean/用户之间共享

javascript - 如何在selenium中控制滚动到底部的速度