如果发生特定异常,请在 selenium 中重新启动测试

Restart Test in selenium if a certain exception occurs

我正在 运行通过 kobiton 进行 selenium 移动测试,我一直发现的一个问题是,当我使用 public 手机时,当我尝试 [=25] 时,它们可能正在使用中=] 测试我收到以下消息

org.openqa.selenium.SessionNotCreatedException: 没有符合所需功能的设备

我当前的代码设置是

@BeforeClass
public void setup()throws Exception{

    String kobitonServerUrl = "https://f:a15e3b93-a1dd3c-4736-bdfb- 
006221ezz8c2a2cz@api.kobiton.com/wd/hub";

    this.driver = new RemoteWebDriver (config.kobitonServerUrl(), 
config.desireCapabilitites_iphone8());

}

我希望能够尝试

    this.driver = new RemoteWebDriver (config.kobitonServerUrl(), config.desireCapabilitites_iphone9() )

如果 iphone 8 不可用,所以我认为 if 和 else 可以工作,但我不知道如何针对特定异常执行此操作?

如果我正确理解你的问题,你想要类似于 if-else 的东西,但有例外,

一般来说 'if-else' 的异常是 'try-catch'。也就是下面的代码片段

try{
   this.driver = new RemoteWebDriver (config.kobitonServerUrl(), config.desireCapabilitites_iphone8());
} catch(Exception e){
   // Do something if any exception is thrown
}

将执行 try 中的内容,如果抛出 any 异常(在 try 中)将执行 [=21] 中的代码=]赶上.

对于特定的异常,您也可以指定异常,前提是您已经导入了它,就像这样

try{
   this.driver = new RemoteWebDriver (config.kobitonServerUrl(), config.desireCapabilitites_iphone8());
} catch(SessionNotCreatedException e){
   // Do something if SessionNotCreatedException is thrown
}

单独捕获异常

@BeforeClass
public void setup()throws Exception{

   try {
    String kobitonServerUrl = "https://f:a15e3b93-a1dd3c-4736-bdfb- 
006221ezz8c2a2cz@api.kobiton.com/wd/hub";

    this.driver = new RemoteWebDriver (config.kobitonServerUrl(), 
config.desireCapabilitites_iphone8());
}

catch (SessionNotCreatedException e){
    this.driver = new RemoteWebDriver (config.kobitonServerUrl(), config.desireCapabilitites_iphone9() )
}

   // if you want to use if else
 catch (Exception other){
      if ( other.getMessage().contains("SessionNotCreatedException ") )
    { 
       // do something
    }

 }

}