Java Selenium异常处理设计

Java Selenium异常处理设计,java,selenium,design-patterns,exception-handling,Java,Selenium,Design Patterns,Exception Handling,为了防止在selenium page对象的每个方法中进行异常处理,我想在测试块中有一个通用的异常处理,一个try-catch, 仅当需要更具体的处理时,才使用其他处理程序 现在的问题是,这个过程需要在每个测试中编写。。。 有没有一种方法可以让测试方法对所有测试都编写一次此通用测试处理 @Test public void test(WebDriver driver) { try { // common code in the try block

为了防止在selenium page对象的每个方法中进行异常处理,我想在测试块中有一个通用的异常处理,一个try-catch, 仅当需要更具体的处理时,才使用其他处理程序

现在的问题是,这个过程需要在每个测试中编写。。。 有没有一种方法可以让测试方法对所有测试都编写一次此通用测试处理

@Test
public void test(WebDriver driver) {        
    try {
        // common code in the try block
        // using testNG may be moved to @BeforeMethod And @AfterMethod
        Logger.log("Test Started....");

        Logger.log("Test Ended....");
        Assert.assertAll();
    }
    catch() {
        // in Case Automation Fails, common operations required 
        ScreenShoot.getScreenShoot(); 
    }
    finally 
    {   
        // finally for all tests    
        driver.close();
    }
}

我建议创建父测试类,所有其他测试都将扩展该类。在这个父测试类中,创建@AfterMethod,它将在失败时截图。下面是一个示例(尽管没有继承):


如果您使用的是jUnit,则可以创建TestWatcher规则(提到了TestNG替代方案
ITestListener

这样,您的测试只包含实际的测试代码,并且您在一个地方完成了所有的准备/拆卸。 每个测试类只需要一个带有
@Rule
注释的公共成员变量,如下所示:

public class OneOfYourTestClasses {
    @Rule
    public TestWatcher watcher = new YourTestWatcherImplementation();

    @Test
    public void testSomething() {
        ...
    }

    @Test
    public void testEvenMore() {
        ...
    }
}

此解决方案是否也像示例代码中的try catch一样处理异常和打印堆栈跟踪?如果出现异常,将调用TestWatcher.failed()方法,并将捕获的错误作为第一个参数。使用这个一次性工具,你可以随心所欲-打印堆栈跟踪、记录它或忽略它-因为jUnit已经注册了错误并将测试运行标记为失败。这个演示正是我搜索的,但它似乎只适用于jUnit,testNG有一种不同的方法,不在BaseTest类中使用@Rule,它使用添加到套件中的中的侦听器,因此只有在我运行套件而不是测试类时侦听器才会工作。
public class OneOfYourTestClasses {
    @Rule
    public TestWatcher watcher = new YourTestWatcherImplementation();

    @Test
    public void testSomething() {
        ...
    }

    @Test
    public void testEvenMore() {
        ...
    }
}