【问题标题】:How can I call few objects of superclass inside different methods in one subclass?如何在一个子类的不同方法中调用几个超类对象?
【发布时间】:2019-08-23 23:04:09
【问题描述】:

我尝试在 Java + Selenium WebDriver 上编写自动化测试,这个特定的测试现在可以正常工作,但在我看来,代码质量存在问题 - 最奇怪的行是在这里为每个测试调用超类的对象.

我尝试通过删除测试方法中的所有对象调用并在类中添加一个对象调用来重构它,但得到了 NullPointerException。

@BeforeTest
public void initialize() throws IOException{
    driver = initializeDriver();
}

@Test
public void sendRecoverEmailValid() {

    ForgotPasswordPage fp = new ForgotPasswordPage(driver);
    fp.AssertForgotPasswordPage();

    fp.setRecoverEmail(validRecoveryEmail);
    fp.pressSendButton();

    RecoverPasswordValidationPage rpvp = new RecoverPasswordValidationPage(driver);
    rpvp.AssertRecoverPasswordValidationPage();

}

@Test
public void sendRecoverEmailInvalid() {

    ForgotPasswordPage fp = new ForgotPasswordPage(driver);
    fp.AssertForgotPasswordPage();

    fp.setRecoverEmail(invalidRecoveryEmail);
    fp.pressSendButton();
    fp.AssertRecoverEmailErrorPresece();

}

@AfterTest
public void shutdown() {
    shutdownDriver();
}

那么,我该如何解决呢? 也许您对 java/selenium 的清晰代码有任何其他建议,请写信。我会很感激的。

非常感谢!

【问题讨论】:

  • 你从哪里得到 NullPointerException?

标签: java selenium oop selenium-webdriver


【解决方案1】:

首先,我建议从页面对象中删除断言,将来它会变成地狱。

rpvp.AssertRecoverPasswordValidationPage(); // no :^C

其次,我认为您不需要过多地忽略变量名称,当您开始执行复杂的测试场景时,它真的很难阅读。这段代码如下:

ForgotPasswordPage fp = new ForgotPasswordPage(driver);

可以变成:

ForgotPasswordPage forgotPasswordPage = new ForgotPasswordPage(driver);

第三,如果你正在使用页面工厂并且你的测试WILL遵循一个顺序(我知道测试应该是独立的,但在 UI 测试中这几乎是一个梦想),你可以在@BeforeTest 部分(请记住,您的页面对象的 @FindBy 内容只有在您第一次使用它之后才会“定位”,所以不要介意在测试类 check this answer about @FindBy 上使用之前创建它)。这段代码如下:

@BeforeTest
public void initialize() throws IOException{
    driver = initializeDriver();
}

会变成:

// in case you are using JUnit, this attributes should be static, don't remember about TestNG. (Nullpointer situation)
private ForgotPasswordPage forgotPasswdPage;
private RecoverPasswordValidationPage recoverPasswdValidationPage;

@BeforeTest
public void initialize() throws IOException{
    driver = initializeDriver();
    forgotPasswdPage = new ForgotPasswordPage(driver);
    recoverPasswdValidationPage = new RecoverPasswordValidationPage(driver);
}

我建议您不要将此代码移动到父类(保持现在的样子),因为如果您计划将来在类级别并行运行,你可能会看到奇怪的事情发生,因为你的测试类共享同一个父类,当我们开始转向并行时,我遇到了超过 50 个类的问题,你的测试类应该控制何时启动和结束 WebDriver。

@BeforeTest
public void initialize() throws IOException{
    driver = initializeDriver();
}

@AfterTest
public void shutdown() {
    shutdownDriver();
}

【讨论】:

    猜你喜欢
    • 2013-04-06
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多