【问题标题】:how to catch loss of internet exception while running a automation test using selenium如何在使用 selenium 运行自动化测试时捕获 Internet 异常的丢失
【发布时间】:2014-11-22 05:10:10
【问题描述】:
我有一个包含 1000 个测试数据的测试套件,它必须使用 selenium 自动化进行测试。
假设我的 500 次测试已经运行并且我失去了互联网连接,我想在这里处理互联网连接异常。
这可以使用 selenium 来完成,或者我们需要一个 3 方工具来处理这个问题。请推荐
提前致谢
【问题讨论】:
标签:
java
selenium
selenium-webdriver
browser-automation
【解决方案1】:
我从未听说过 selenium web 驱动程序,但是,当特定时间过去时会抛出一个异常,由 Selenium 提供,即org.openqa.selenium.TimeoutException()(假设失去连接是超时的原因之一)
所以我们提出了一个真正的使用需求,即由一个名为 Future 的接口提供的异步调用
A Future represents the result of an asynchronous computation
如 Javadoc 所述
其中有一个方法get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException
所以你可以使用它,
在更改了 Oracle Javadoc 提供的示例使用代码后,我想出了一些可以解决您的问题的方法
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
interface ArchiveSearcher {
String search(String target) throws InterruptedException;
}
class ArchiveSearcherClass implements ArchiveSearcher {
ArchiveSearcherClass() {
}
@Override
public String search(String target) throws InterruptedException {
synchronized (this) {
this.wait(2000); //in your case you can just put your work here
//this is just an example
if (("this is a specific case that contains " + target)
.contains(target))
return "found";
return "not found";
}
}
}
class App {
ExecutorService executor = Executors.newSingleThreadExecutor();
ArchiveSearcher searcher = new ArchiveSearcherClass();
void showSearch(final String target)
throws InterruptedException {
Future<String> future
= executor.submit(new Callable<String>() {
public String call() throws InterruptedException {
return searcher.search(target);
}});
System.out.println("remember you can do anythig asynchronously"); // do other things while searching
try {
System.out.println(future.get(1, TimeUnit.SECONDS)); //try to run this then change it to 3 seconds
} catch (TimeoutException e) {
// TODO Auto-generated catch block
System.out.println("time out exception");
// throw new org.openqa.selenium.TimeoutException();
} catch (ExecutionException e) {
System.out.println(e.getMessage());
}
}}
public class Test extends Thread {
public static void main(String[] args) {
App app1 = new App();
try {
app1.showSearch("query");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}