Search code examples
javaselenium-webdriverdependency-injectioncucumberpicocontainer

How to effectively use PicoContainer Setter Injection (Use PicoContainer without passing parameters to the constructor)?


How to effectively use PicoContainer Setter Injection?

I need to be able to pass data across Cucumber steps and want to avoid the traditional PicoContainer approach where parameters are passed to the constructor (Use PicoContainer without taking the approach of injecting classes inside of other classes via the constructor).

So far I have the following setup with no luck, any ideas?

My steps class:

public class MainSteps extends Base {

    DefaultPicoContainer pico = new DefaultPicoContainer(new SetterInjection("init"));

    public MainSteps() {
        this.pico.addComponent(Account_Pojo.class);
    }

    @Given("^I went to the farmm$")
    public void i_went_to_the_farm() {
        loadUrl(Global_Vars.HOMEPAGE_URL);
        Account_Pojo account_pojo = pico.getComponent(Account_Pojo.class);
        account_pojo.setFirstName("joe");
        System.out.println(account_pojo.getFirstName()); //outputs joe
    }

    @Given("^I went to the zoo$")
    public void i_went_to_the_zoo() {
        Account_Pojo account_pojo = pico.getComponent(Account_Pojo.class);
        System.out.println(account_pojo.getFirstName()); //null pointer exception
    }
    }

Pojo Setup:

public class Account_Pojo {
    private String firstName;

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getFirstName() {
        return firstName;
    }
}

As you can see from the above code, the following line of code situated within the second step should return joe however it seems to be returning a null value instead:

System.out.println(account_pojo.getFirstName()); //null pointer exception

Solution

  • Change the firstName to static like

    private static String firstName;
    

    OR

    Pass the same object reference where you doing

    System.out.println(account_pojo.getFirstName());