javaseleniumwebdriverjbehavepageobjects

How can I use a variable in many PageObjects with JBehave?


For example:

Scenario:
Given the pageOne page
When I get pageOneTitle
And click the first menu item
And I get the pageTwoTitle
Then pageOneTitle is not equals pageTwoTitle

I have two steps classes. One for each page.

The first three steps of the scenario are in PageOneSteps and the other in PageTwoSteps. That means, that pageTitleOne was saved in PageOneSteps. The verify step Then pageOneTitle is not equals pageTwoTitle is in PageTwoSteps.

How can I equals pageOneTitle and pageTwoTitle in PageTwoSteps, if pageOneTitle is in PageOneSteps?

This is a very simple example. But I hope it illustrate what I mean.

Thanks for your support!


Solution

  • You can use a context in which you put the objects/values needed by more than one of your StepClasses when executing a story. This can be implemented using ThreadLocal. Using such a context, you can simply put the value you get in the second step into the context and get it again in the fifth step where it is needed for the comparison. Examples how to use ThreadLocal can be found easily—e.g. here.

    Maybe the most simple example is as follows (see the linked page above for more information).

    Story:

    Scenario: store and load a value
    When I store the value asdf
    Then the value is asdf
    

    Class Context:

    public class Context {
        private String data;
        // getData(), setData(), ...
    }
    

    Class MyThreadLocal:

    public class MyThreadLocal {
        static final class ContextLocal extends ThreadLocal<Context> {
            @Override
            protected Context initialValue() {
                return new Context();
            }
        }
    
        private static final ThreadLocal<Context> userThreadLocal = new ContextLocal();
    
        public static Context get() {
            return userThreadLocal.get();
        }
    }
    

    And the steps classes:

    public class SomeSteps extends Steps {
        @When("I store the value $value")
        public void storeValue(String value) {
            MyThreadLocal.get().setData(value);
        }
    }
    
    public class SomeOtherSteps extends Steps {
        @Then("the value is $value")
        public void checkValue(String value) {
            assertEquals(value, MyThreadLocal.get().getData());
        }
    }
    

    In the class Context you can use more elaborate ways to store data, e.g. a Map.