如何在Selenium 2中的类中共享@Before和@Test?

时间:2013-12-13 20:03:05

标签: java selenium

我的所有课程中都有以下两种方法:

@Before
public void setUp() throws Exception {      
    WebDriver driver = new FirefoxDriver();
    String baseUrl = "http://trn-test-web.fon.com/";
    selenium = new WebDriverBackedSelenium(driver, baseUrl);
}

@Test
public void firstTest() throws Exception{
    selenium.open("/opencase/login.seam");
    selenium.type("//input[contains(@id, ':username')]", "admin");
    selenium.type("//input[contains(@id,':mypassword')]", "admin");
    selenium.click("//a[contains(@id,'loginForm:')]/span");
    selenium.waitForPageToLoad("60000");        
    _wait("Home", "id=oc-title-id");
}

如何与项目中的其他类共享@Before@Test方法,这样他们就不会打开自己的登录页面并使用相同的baseUrl并在类中登录?

2 个答案:

答案 0 :(得分:3)

您可以创建将通过测试扩展的类(TestBase)

public class TestBase {

    protected WebDriver driver;
    protected Selenium selenium

@Before
public void setUp() throws Exception {      
    driver = new FirefoxDriver();
    String baseUrl = "http://trn-test-web.fon.com/";
    selenium = new WebDriverBackedSelenium(driver, baseUrl);
}

@Test
public void firstTest() throws Exception{
    selenium.open("/opencase/login.seam");
    selenium.type("//input[contains(@id, ':username')]", "admin");
    selenium.type("//input[contains(@id,':mypassword')]", "admin");
    selenium.click("//a[contains(@id,'loginForm:')]/span");
    selenium.waitForPageToLoad("60000");        
    _wait("Home", "id=oc-title-id");
}

这里如何使用

public class ExampleTest extends TestBase {

@Test
public void secondTest() throws Exception {
     selenium.open("http://stackoverflow.com/");
}

现在每次运行类ExampleTest时,它都会运行 firstTest secondTest

答案 1 :(得分:1)

执行此操作的最佳方法是将@Before方法放在抽象类中,例如AbstractUITest,并使所有测试都从该类继承,每次测试运行时都会这样,@在从抽象类执行方法之前,所有方法都可以使用baseUrl。