在框架中启动页面的好习惯

时间:2018-03-13 17:31:25

标签: java selenium automation

我正在创建测试框架。

如果我在类中的@BeforeClass中启动我的网站的所有页面,并且由Testcase类扩展,这是否合适?

        public class TradeService {

            /*
             * This file provides connection to the DB for the TradeMessage object
             * */

            SessionFactory sessionFactory =  null;
            Session session = null;


            public TradeService() {
                super();
                SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
                this.sessionFactory = sessionFactory;
                this.session = sessionFactory.openSession(); 
            }

            public List<TradeMessage> getTradeMessages(TradeMessageFilterBean filterBean){
                List<TradeMessage> queryResult = new ArrayList<>();
                //. . .
                return queryResult;
            }
        }

或者如果我在每个测试案例中都更好:

public class ConfigurationForBrowser {
@BeforeClass(alwaysRun = true)
public void browserSetup() throws Exception{

    this.driver = getDriver(DriverFactory.getBrowserTypeByProperty());

    registrationPage = 
    PageFactory.initElements(driver,RegistrationPage.class);
    homePage = 
    PageFactory.initElements(driver,HomePage.class);
 ...

}

或许在每个测试用例中都有更好的方法可以摆脱BeforeClass?

1 个答案:

答案 0 :(得分:0)

正如SiKing在评论中提到的,我发现在构造函数中调用 PageFactory.InitElements(driver,this)是可行的方式,这样你就不会不必要地初始化类了不需要BeforeClass的东西。

我使用的一些C#代码应该明白:

public class HomePage
{
    private readonly IWebDriver _driver;

    public HomePage(IWebDriver driver)
    {
        _driver = driver;
        PageFactory.InitElements(driver, this);
    }

    [FindsBy(How = How.Id, Using = "login")]
    public IWebElement LogInButton { get; set; }

    public LoginPage ClickLogin()
    {
        LogInButton.Click();

        // Page object chaining, you could use a void return type instead
        return new LoginPage(_driver);
    }
}

然后在你的测试中:

[Test]
public void TestLogin()
{
    // Elements get initialized in the constructor, so you don't have to call it explicitly
    var homePage = new HomePage(Driver);

    var loginPage = homePage.ClickLogin();

    loginPage.Login("username", "password");

    Assert.True(someCondition);
}