Многопоточный запуск Selenium тестов из JUnit
Подумал я как-то а не заранить ли мне тесты в потоках, а не последовательно один за одним. Погуглил немного и нашел как раз то что мне надо было. Я реализовал эту идею немного переделав код из примера с JUnit. Тестируемые страницы остались те же. Реализация проста и можно запускать тесты в потоках, но есть одно «но», а в будущем может оказаться и больше. Мы их рассмотрим попозже. Будем использовать стандартные классы java для работы с потоками. Приступим.
Для начала создадим packages: automation и automation.multithread. Положим в automation.multithread следующие классы:
MultiThreadedTestCase.java
import junit.framework.*;
public class MultiThreadedTestCase extends TestCase {
private Thread threads[] = null;
private TestResult testResult = null;
public MultiThreadedTestCase(String s) {
super(s);
}
public void interruptThreads() {
if(threads != null) {
for(int i = 0;i < threads.length;i++) {
threads[i].interrupt();
}
}
}
public void run(final TestResult result) {
testResult = result;
super.run(result);
testResult = null;
}
protected void runTestCaseRunnables (final TestCaseRunnable[] runnables) {
if(runnables == null) {
throw new IllegalArgumentException("runnables is null");
}
threads = new Thread[runnables.length];
for(int i = 0;i < threads.length;i++) {
threads[i] = new Thread(runnables[i]);
}
for(int i = 0;i < threads.length;i++) {
threads[i].start();
}
try {
for(int i = 0;i < threads.length;i++) {
threads[i].join();
}
}
catch(InterruptedException ignore) {
System.out.println("Thread join interrupted.");
}
threads = null;
}
/**
* Handle an exception. Since multiple threads won’t have their
* exceptions caught the threads must manually catch them and call
* <code>handleException ().
* @param t Exception to handle.*/
public void handleException(final Throwable t) {
synchronized(testResult) {
if(t instanceof AssertionFailedError) {
testResult.addFailure(this, (AssertionFailedError)t);
}
else {
testResult.addError(this, t);
}
}
}
}

