gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:15:12 27 4
gpt4 key购买 nike

我正在尝试使用 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com