In the previous cucumber-jvm post I introduced dependency injection, which makes it possible to use mocks during testing. Usually, it is a bad idea to introduce mocks in cucumber scenarios, because they are supposed to test the whole system as it is, however there are cases when mocking comes in handy: for example, a module or component of your system communicates with a 3rd party system. In this case, running the scenarios may be difficult, and the best option here is to mock or simulate that 3rd party system so that your application or product can still be tested. Technically, it is really easy to use mocks with cucumber-jvm, but there are certain limitations, which you’ll see at the end of this post.
Let’s say that the munger functionality in our SimpleTextMunger application is a 3rd party system, which communicates through the network, but that network is not reachable from our test system. Here is the current code:
public String execute(String sentence) { List words = sentenceHelper.split(sentence); for (int i = 0; i < words.size(); i++) { words.set(i, munger.munge(words.get(i))); } return sentenceHelper.join(words); }
In order to mock the calls of the munger object we need something like this – I’m going use mockito as a mocking framework:
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; // ... when(munger.munge(inputWord)).thenReturn(mungedWord); // ...

