首页 文章

如何在TestNG测试中包含自己的线程中的测试成员?

提问于
浏览
2

我试图使用TestNG作为跑步者并行运行我的硒测试 . 并行需求在testng.xml文件中设置如此 .

<test name="smoke tests" parallel="methods" thread-count="2">

我遇到的问题是我想在每次测试后“退出”浏览器 . 然后我启动一个新的浏览器并运行下一个测试 . 这对我来说效果很好,直到我尝试并行运行测试 . 似乎这些方法共享线程,如果你退出浏览器,那么线程现在就消失了 . TestNG尝试在退出的线程上运行下一个测试,我收到SessionNotFoundException错误 .

我尝试了parallel =“tests”但是这不起作用,测试按顺序而不是并行运行 . 有没有办法在新线程中运行每个测试而不是重用线程或我运气不好?

这是我的@BeforeMethod

private static ThreadLocal<WebDriver> driverForThread;

@BeforeMethod
public static void setUpMethod() {
    log.info("Calling setup before method");

    driverForThread = new ThreadLocal<WebDriver>() {

        @Override
        protected WebDriver initialValue() {
            WebDriver driver = loadWebDriver();
            driver.manage().window().maximize();
            return driver;
        }
    };
}

还有我的@AfterMethod

@AfterMethod
public static void afterMethod() {
    getDriver().quit();
}

public static WebDriver getDriver() {
    return driverForThread.get();
}

这是一个示例测试

@Test
public void shouldBeAbleToGetSessionIDTest() {
    login = new LoginPage(getDriver()).get();
    home = login.loginWithoutTelephony(username, password); 
    String sessionID = home.getSessionID();
    Assert.assertNotNull(sessionID);
    log.info("The session text is: " + sessionID);
}

1 回答

  • 1

    TestNG为注释为 @Test 的方法内置了线程 . 当我遇到这个问题时,那是因为我没有穿过我的WebDriver . 指定 parallel="methods" 的XML配置是正确的 .

    在类级别,声明两个ThreadLocal对象,一个具有WebDriver类型,另一个具有DesiredCapabilities类型:

    ThreadLocal<DesiredCapabilities> capabilities = new ThreadLocal<DesiredCapabilities>();
    ThreadLocal<WebDriver> driver = new ThreadLocal<WebDriver>();
    

    然后,在 @BeforeMethod 中,您需要使用适当类型的新实例初始化它们,配置并启动WebDriver .

    capabilities.set(new DesiredCapabilities());
    capabilities.get().setBrowserName("Firefox");
    driver.set(new RemoteWebDriver(new URL("url of your grid hub"), capabilities.get()));
    

    您需要在方法中添加throws声明或在try / catch中包装 driver.set() .

    在测试结束时,线程将与DesiredCapabilities和WebDriver一起关闭 . 但是,如果要手动关闭它们,可以使用适当的调用在 @AfterMethod 中执行此操作(请参阅ThreadLocal JavaDoc) .

    这将生成一个设置,该设置将在新的浏览器中启动每个 @Test 方法,该浏览器将在执行结束时关闭 .

    另外,DesiredCapabilities为您的测试环境提供了丰富的配置选项 . 所有支持选项,如指定浏览器,浏览器版本,操作系统平台,甚至浏览器配置(如禁用js等) . 使用此方法,Grid将在支持给定条件的节点上运行测试 .

    希望你会发现这很有帮助 . 我遇到了你描述的确切问题,这就是为我解决的问题 .

相关问题