1
User user1;

Given("Add a new User profile")
public void addUser(){
PageFactory.initElements(driver, User.class);
user1.enterName(...);
}

Then("Edit a existing User profile")
public void editUser(){
PageFactory.initElements(driver, User.class);
user1.updateEmail();
}

Now, I need to use the WebElements that are defined in the "User.java" class in every test step of a scenario?

Why do we need to do this? Else, I get a NullPointerException, if I don't initialize under each step. Is each Step in the Cucumber scenario treated as a different Class?

1 Answer 1

1

Cucumber uses its own mechanism to instantiate objects (aka dependencies) which are referenced as glued classes fields or parameters of glued classes methods.

It uses ObjectFactory that by default creates new instance for each field/parameter on each scenario step.

The conditions which determine if the same field would reference the same object is called "a scope" (a term from dependency injection) so default scope is scenario step.

If you want to extend the scope you should integrate your code with DI extension of cucumber. It will allow to use Scenario-scoped references which means that you will "see" the same object from different steps of scenario.

There are several DI frameworks which Cucumber can integrate with. Here you can find the example of how to implement Page Object pattern with PicoContainer framework with cucmber-java8. And here you can find the example of how to implement PageObject with the help of Guice and classic cucumber-java.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.