有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在一个子类中调用不同方法中的几个超类对象?

我尝试在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的清晰代码的建议,请写下。我会非常感激的

非常感谢


共 (1) 个答案

  1. # 1 楼答案

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

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

    第二,我不认为你需要省去那么多变量名,当你开始做复杂的测试场景时,读起来真的很难。此代码如下:

    ForgotPasswordPage fp = new ForgotPasswordPage(driver);
    

    可以变成:

    ForgotPasswordPage forgotPasswordPage = new ForgotPasswordPage(driver);
    

    第三,如果你正在使用PageFactory,你的测试将遵循一个顺序(我知道测试应该是独立的,但在UI测试中,这几乎是一个梦想),您可以在@BeforeTest部分实例化页面(请记住,页面对象的@FindBy things只有在您第一次使用它之后才会被“定位”,所以不要介意在测试类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();
    }