0

I've browsed over internet to get the relevant info but no luck. The example code is given below :

public class HomePage 
{
    @FindBy(id = "fname")
    WebElement name;

    @FindBy(id = "email")
    WebElement email;

    @FindBy(id = "password")
    WebElement password;

    @FindBy(id = "passwordConf")
    WebElement confPassword;

    public HomePage fillFormDetails(String firstname, String emailid)
    {
        name.sendKeys(firstname);
        email.sendKeys(emailid);

        return this;
    }

    public void fillPass(String pass)
    {
        password.sendKeys(pass);

    }   
}

I want to know why we are returning the object while calling fillFormDetails(String firstname, String emailid) method ?

What could be the usecases so we can use this to manage our code efficiency ?

4

2 回答 2

1

The returned object is used when you want to us methods chaining

HomePage homePage = new HomePage();
homePage
    .fillFormDetails(firstName, email)
    .fillPass(pass);

As a side note, better design is to split all the actions to separated methods, instead of just some of them

public HomePage fillFirstName(String firstName)
{
    name.sendKeys(firstName);

    return this;
}

public HomePage fillEmail(String email)
{
    email.sendKeys(email);

    return this;
}

public void fillPass(String pass)
{
    password.sendKeys(pass);
}

And in the test

HomePage homePage = new HomePage();
homePage
    .fillFirstName(firstName)
    .fillEmail(email)
    .fillPass(pass);
于 2017-08-09T13:22:40.020 回答
1

这称为方法链。更多在这里。 https://en.wikipedia.org/wiki/Method_chaining#Java

假设您在一个类中有三个方法来填写用户名、填写密码和最后提交表单。

通常您会创建页面的对象,并使用该对象单独调用它们。像这样的东西,

MethodChaining methodChaining = new MethodChaining();
methodChaining.fillUserName("username");
methodChaining.fillPassword("password");
methodChaining.submit();

但是,如果您返回同一类的对象,则this可以按以下方式链接方法。

有时它很方便,而且看起来不错:)

public class MethodChaining {

    public MethodChaining fillUserName(String username){
        return this;
    }

    public MethodChaining fillPassword(String password){
        return this;
    }

    public MethodChaining submit(){
        return this;
    }

    public static void main(String args[]){
        MethodChaining methodChaining = new MethodChaining();
        methodChaining.fillUserName("abc")
                .fillPassword("pass")
                .submit();
    }
}

现在天气是否在自动化中使用它完全取决于应用程序的人和行为。

如果你有一个严格的单一流程,那么多个流程真的很难处理。这可能很好。

对于多流。假设当您提交此表单时,您要么登录,要么停留在显示错误的同一页面上。现在要做到这一点,你必须Submit用一些逻辑来处理这个函数。这有时会变得复杂并在您必须维护它时产生问题。

于 2017-08-09T13:24:13.020 回答