黄瓜@Before挂钩运行两次@After一次

时间:2019-02-21 22:32:04

标签: selenium-webdriver cucumber selenium-chromedriver junit5 cucumber-junit

全部。 用Java11 + Junit5 + Cucumber + Selenium编写一个BDD Test自动化框架,构建工具:Graddle。创建了一个用于验证Google标题的小测试。在开始测试时,在Graddle中使用Test task或运行CucumberRunner类,在两种情况下都得到相同的结果:两次执行@Before方法,一次执行@After方法,一个浏览器窗口保持打开状态。添加了一个以上的测试后,相同的情况,仅打开了4个浏览器,其中2个正在关闭。有人可以解决这种情况吗?

Link to repository

在看完日志后,似乎@Before没有执行两次,但是Driver类被初始化了两次,但是为什么现在暂时不知道...

我现在的代码: CucumberRunner.java

@RunWith(Cucumber.class )
@CucumberOptions(
        features = "src\\test\\java\\features",
        glue = {"steps", "utils"},
        tags = "@smoke")
public class CucumberRunner {
}

Driver.java

public class Driver {
    private WebDriver driver;

    public Driver(){
        driverInitialization();
    }

    private void driverInitialization(){
        System.setProperty("webdriver.chrome.driver", "D:\\Soft\\selenium-drivers\\chromedriver.exe");
        System.out.println("Starting driver.");
        var browserName = "chrome";
        switch (browserName.toLowerCase()){
            case "chrome":
                System.out.println("Starting chrome");
                driver = new ChromeDriver();
                System.out.println("Before break.");
                break;
            case "firefox":
                driver = new FirefoxDriver();
                break;
            default:
                throw new NotFoundException("Browser not found: " + browserName);
        }
    }

    public WebDriver getDriver(){
        return driver;
    }

    public WebDriverWait getWebDriverWait(){
        return new WebDriverWait(driver, 120);
    }

    public void terminateDriver(){
        System.out.println("Terminating driver.");
        if (driver != null) {
            driver.close();
            driver.quit();
        }
    }
}

Hooks.java

public class Hooks {
    private Driver driver;

    @Before
    public void setup(){
        System.out.println("In the Setup method.");
        driver = new Driver();
    }

    @After
    public void tearDown(){
        System.out.println("In the TearDown method.");
        driver.terminateDriver();
    }
}

1 个答案:

答案 0 :(得分:2)

我认为您在使用Selenium-picocontainer DI时,您的Hook类应该像这样。

public class Hooks {

private Driver driver;

public Hooks(Driver driver) {
    this.driver = driver;
   }

@Before
public void setup(){
    System.out.println("In the Setup method.");
   }

@After
public void tearDown(){
    System.out.println("In the TearDown method.");
    driver.terminateDriver();
   }
}