简体   繁体   English

几个测试类后关闭浏览器

[英]Close browser after several test classes

I work on an automated testing framework and I need to close the browser after passing tests on several test classes.我在一个自动化测试框架上工作,我需要在通过几个测试类的测试后关闭浏览器。

The package structure of the project is similar to this:工程的package结构类似这样:

  • PackageA包A
    • SomeTestClass1 SomeTestClass1
    • SomeTestClass2 SomeTestClass2
    • ... ...
  • PackageB包B
    • SomeOtherTestClass1 SomeOtherTestClass1
    • SomeOtherTestClass2 SomeOtherTestClass2
    • ... ...

Note: There can be multiple levels of packages inside one another.注意:相互之间可以有多个级别的包。

If I use @AfterClass or @AfterAll JUnit annotations I have to close the browser at the 'end' of each test class.如果我使用 @AfterClass 或 @AfterAll JUnit 注释,我必须在每个测试 class 的“末尾”关闭浏览器。 My framework requires launching the browser (as a static variable) and closing it only one time to speed up execution and avoid losing time for every browser launch and login, as I currently have a big number of tests that need to be run each night.我的框架需要启动浏览器(作为 static 变量)并仅关闭一次以加快执行速度并避免每次浏览器启动和登录都浪费时间,因为我目前有大量的测试需要每晚运行。

Is there any possiblity I could achieve this behaviour?我有没有可能实现这种行为?

In JUnit 4 , you could use the concept of Rule in conjunction with extending TestWatcher abstract class ( org.junit.rules.TestWatcher ).JUnit 4中,您可以将Rule的概念与扩展TestWatcher抽象 class ( org.junit.rules.TestWatcher ) 结合使用。 Hence you won't have to close the browser in a method annotated with @AfterClass .因此,您不必在使用@AfterClass注释的方法中关闭浏览器。

eg例如

public class StartFinishTestWatcher extends TestWatcher {
    @Override
    protected void starting(Description description) {
        System.out.println("Starting test: " + description.getDisplayName());
    }

    @Override
    protected void finished(Description description) {
        System.out.println("Finishing test: " + description.getDisplayName());
        // close the browser here
    }
}

Then you would use this class in a RuleChain , in the test class(es) where you want to close the browser.然后,您将在要关闭浏览器的测试类中的RuleChain中使用此 class 。

public class MyTestInWhichIWantBrowserToClose {

    @Rule
    public RuleChain ruleChain = buildTestRuleChain();

    private RuleChain buildTestRuleChain() { // could be made protected and put in a superclass

        return RuleChain.outerRule(new StartFinishTestWatcher());
    }
}

In JUnit 5 you could create custom Test Suites and implement BeforeTestExecutionCallback and (in your case) AfterTestExecutionCallback interfaces in one of your base class.JUnit 5中,您可以在基础 class 之一中创建自定义 测试套件并实现BeforeTestExecutionCallback和(在您的情况下) AfterTestExecutionCallback接口。

You would then implement the custom logic which decides to close the browser in method public void afterTestExecution(ExtensionContext context) .然后,您将实现决定在方法public void afterTestExecution(ExtensionContext context)中关闭浏览器的自定义逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM