small medium large xlarge

06 Oct 2017, 14:18
Kieran Whooley (1 post)

Hi, I have a fairly stupid question but I am stumped so any help would be great.

This scenario in the Try This section of Chapter 2:

Scenario: Two bananas scanned separately Given the price of a “banana” is 40c When I checkout 1 “banana” And I checkout 1 “banana” Then the total price should be 80c

When calling the same step in a scenario twice is it creating two separate objects in Checkout. one for each step?

If so how do I handle this?

I’m fairly new to this so apologies if this makes no sense. Thanks

06 Oct 2017, 22:23
Seb Rose (19 posts)


Not a stupid question at all.

Cucumber creates one CheckoutSteps object for each scenario. How you manage the Checkout object is the responsibility of your code.

As you’ve noticed, the example implementation of CheckoutSteps creates an instance of Checkout in the When I checkout step. So, if your scenario repeats that phrase (as you’re asked to do in the Try this section at the end), two Checkout objects will get created and the scenario will fail.

To get the scenario to pass, you need to move the creation of the Checkout object. One possible solution is:

public class CheckoutSteps {
    Checkout checkout = new Checkout();
    int bananaPrice = 0;

    @Given("^the price of a \"(.*?)\" is (\\d+)c$")
    public void thePriceOfAIsC(String name, int price) throws Throwable {
        bananaPrice = price;

    @When("^I checkout (\\d+) \"(.*?)\"$")
    public void iCheckout(int itemCount, String itemName) throws Throwable {
        checkout.add(itemCount, bananaPrice);

    @Then("^the total price should be (\\d+)c$")
    public void theTotalPriceShouldBeC(int total) throws Throwable {

Hope that helps


You must be logged in to comment