Testing external services using Mockito in Cuke4Duke

When developing a system, you often end up in situations where you are depending on external components like web services. In this post I’ll show you how you can use Mockito for mocking up fake responses, and verifying behaviour when using Cuke4Duke.

Lets start with a simple scenario. We want to verify that we call a web service with the correct parameters after processing a message. For this scenario I have created the interface of the web-service we want to verify behaviour from.

First we have to create a mock of the web service interface in spring config. We do this in spring so we can autowire the mock into services.

<bean id="sampleWsPortType" class="org.mockito.Mockito" factory-method="mock">
    <constructor-arg value="no.bekk.ws.SampleWsPortType"/>
</bean>

The next step is to make a cucumber step for verifying that the service is called

@StepDefinitions
public class WsSteps {
    @Resource(name = "sampleWsPortType")
    private SampleWsPortType sampleWsPortType;
    ......
    @Then("the person service receives person with name '(.*?)' and age '(.*?)':")
    public void personServiceReceivesInput(String name, Integer age) {
        ArgumentCaptor<WsPerson> capturedPerson = ArgumentCaptor.forClass(WsPerson.class);
        verify(sampleWsPortType).addPerson(capturedPerson.capture());
        assertEquals(name, capturedPerson.getValue().name);
        assertEquals(age, capturedPerson.getValue().age);
    }
}

You can then use this step definition in a cucumber test.

  Scenario: Post person data and verify that it is sent to the web service with correct parameters
    When I post the line '29;Ola Normann'
    Then the person service receives person with name 'Ola Normann' and age '29'

The next step is mocking response from the service. Use this when you are in need of data from a web service in your code. Open-ID integration for example.

We do this using a Given step in cucumber.

  Scenario: I want to get the correct age for a person.
    Given the web service returns '29' when queried for the age of 'Ola Normann'
    When I submit a request for the age for 'Ola Normann'
    Then the result is '29' returned

To get this working we have to add a step definition to mock the return. We do this with Mockito’s “when” statement.

    @Given("the web service returns '(.*?)' when queried for the age of '(.*?)'")
    public void personServiceShouldReturn(Integer age, String name) {
        when(sampleWsPortType.getAge(eq(name))).thenReturn(age);
    }
  • Jøran Vagnby Lillesand

    This is actually very useful. Do you use XML based application config in src/test in order to have your mocked beans injected?