1

I'm using cucumber and maven on eclipse and what I'm trying to do is run each test independently. For example I have a library system software that basically allows users to borrow books and do other stuff.

One of the conditions is that users can only borrow a max of two books so I wrote to make sure that the functionality works. This is my feature file:

Scenario: Borrow over max limit
Given "[email protected]" logs in to the library system
When "[email protected]" order his first book with ISBN "9781611687910"
And "[email protected]" orders another book with ISBN "9781442667181"
And "[email protected]" tries to order another book with ISBN "1234567890123"
Then jim will get the message that says "The User has reached his/her max number of books"

I wrote a corresponding step definition file and every worked out great. However, in the future I want to use the same username ("[email protected]") for borrowing books as though [email protected] has not yet borrowed any books. I want each test to be independent of each other.

Is there any way of doing this...maybe there's something I can put into my step definition classes such as a teardown method. I've looked into it but I couldn't fine any solid information about it. If there's a way please help me. Any help is greatly appreciated and I thank you in advance!

2

2 Answers 2

1

Yes, you can do setups and teardowns before and after each scenario, but it's not in the step definition file. What you want to use are hooks.

Hooks run before or after a scenario and can run before/after every scenario or just the ones you and @tag to, for example:

@remove_borrowed_books
Scenario: Borrow over max limit

Unfortunately I have only used cucumber with ruby not java so I can't give you step-by-step instructions, but this should tell you what you need to know https://zsoltfabok.com/blog/2012/09/cucumber-jvm-hooks/

1

You can use the "@After" hook to achieve this as @Derek has mentioned using for example a Map of books borrowed per username:

private final Map<String, Integer> booksBorrowed = new HashMap<>();

@After
public void tearDown() {
  booksBorrowed.clear();
}

@Given("...")
public void givenUserBorrowsBook(String username) {
  booksBorrowed.put(username, booksBorrowed.containsKey(username) ? booksBorrowed.get(username) + 1 : 1);
  ....
}

Or the "@Before" hook to perform the cleanup before each scenario is executed, which is the option I would recommend:

private Map<String, Integer> booksBorrowed;

@Before
public void setUp() {
  booksBorrowed = new HashMap<>();
}

If you are planning to run scenarios in parallel then the logic will be more complex as you will need to maintain the relationship between the thread executing a particular scenario and the usernames used on that thread.

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