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