2015-09-18 1 views
2

Я запускаю тесты Selenium, и я не хочу, чтобы нить заканчивалась, поэтому я ломаю все, что могу. Это структура моей программыИсключение и невозможность попадания в ловушку

Мои Main.java

for (int i = 0; i < numberOfThreads; i++) 
{ 
    System.out.println("Inside loop to create threads!"); 
    System.out.println("Number of threads to create: " + numberOfThreads); 
    totalNumberOfThreads++; 
    String threadName = "Thread" + totalNumberOfThreads; 
    if (type.contains("auto")) 
    { 
     newThread = new Thread(new Test()); 
    } 

    UncaughtExceptionHandler handler = new UncaughtExceptionHandler() 
    { 
     @Override 
     public void uncaughtException(Thread t, Throwable ex) 
     { 
      FileOutputStream fos = null; 
      try 
      { 
       fos = new FileOutputStream(new File("throwable.txt"), true); 
      } 
      catch (FileNotFoundException e) 
      { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      PrintStream ps = new PrintStream(fos); 
      ex.printStackTrace(ps); 
     } 
    }; 

    newThread.setName(threadName); 
    newThread.setUncaughtExceptionHandler(handler); 
    newThread.start(); 
} 

Test.java

public class Test extends Common implements Runnable 
{ 
    @Override 
    public void run() 
    { 
     WebDriver driver = null; 
     while (true) 
     { 
      try 
      { 
       driver = new PhantomJSDriver(caps); 
       // bunch of test code 
      } 
      catch (Exception e) 
      { 
       e.printStackTrace(); 
      } 
      catch (Throwable t) 
      { 
       t.printStackTrace(); 
      } 
      finally 
      { 
       driver.quit(); 
      } 
     } 
    } 
} 

Хотя я и ловить исключения и Throwables в Test.java я все еще вижу следующее исключение в throwable.txt время от времени, что означает, что ошибка не попадает в Test.java

org.openqa.selenium.remote.UnreachableBrowserException: Error communicating with the remote browser. It may have died. 
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 02:56:46' 
System info: host: 'localhost', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.1.5-x86_64-linode61', java.version: '1.8.0_60' 
Driver info: driver.version: RemoteWebDriver 
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:589) 
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:618) 
    at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:464) 
    at myprogram.Test.run(Test.java:155) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: org.openqa.selenium.WebDriverException: The PhantomJS/GhostDriver server has unexpectedly died! 
Build info: version: '2.47.1', revision: '411b314', time: '2015-07-30 02:56:46' 
System info: host: 'localhost', ip: '127.0.0.1', os.name: 'Linux', os.arch: 'amd64', os.version: '4.1.5-x86_64-linode61', java.version: '1.8.0_60' 
Driver info: driver.version: RemoteWebDriver 
    at org.openqa.selenium.phantomjs.PhantomJSCommandExecutor.execute(PhantomJSCommandExecutor.java:88) 
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:568) 
    ... 4 more 
Caused by: org.apache.http.conn.HttpHostConnectException: Connect to localhost:30041 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused 
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:151) 
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) 
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) 
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) 
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) 
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) 
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) 
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) 
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71) 
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55) 
    at org.openqa.selenium.remote.internal.ApacheHttpClient.fallBackExecute(ApacheHttpClient.java:143) 
    at org.openqa.selenium.remote.internal.ApacheHttpClient.execute(ApacheHttpClient.java:89) 
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:134) 
    at org.openqa.selenium.phantomjs.PhantomJSCommandExecutor.execute(PhantomJSCommandExecutor.java:82) 
    ... 5 more 
Caused by: java.net.ConnectException: Connection refused 
    at java.net.PlainSocketImpl.socketConnect(Native Method) 
    at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) 
    at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) 
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) 
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) 
    at java.net.Socket.connect(Socket.java:589) 
    at org.apache.http.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74) 
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134) 
    ... 18 more 
+1

что у вас на линии 155 испытаний класса? 'myprogram.Test.run (Test.java:155)' ... не 'driver.quit()'? – Pras

+0

driver.quit(); который находится в блоке finally. теперь я вижу, что происходит. Спасибо – Arya

+2

Боковое примечание по качеству кода: тестовый код так же важен, как и производственный код; поэтому он должен быть написан с тем же контролем, что и тот. В этом смысле: когда-либо читал «Чистый код» Роберта Мартина? – GhostCat

ответ

2

Проверяя stacktrace, вы можете видеть, что исключение вызывается драйвером .quit(), в конце. Если вы хотите, чтобы поймать thoses, вы должны окружить вызов бросить() другую попытку {}

at org.openqa.selenium.remote.RemoteWebDriver.quit(RemoteWebDriver.java:464) 
at myprogram.Test.run(Test.java:155) 
0

Ваши окончательно еще не окружен TRY/уловом.

Вам нужно что-то вроде:

finally{ 
     try{ 
     driver.quit(); 
     }catch(Exception ex){ 
     //do something 
     } 
    } 
Смежные вопросы