Popular Posts

Client side REST Testing

Test Scenario: Test when server throw 400 BAD_REQUEST exception, PetStoreClient should throw BadRequestException

Demonstration of client-side REST testing using MockRestServiceServer

— tvajjala

This tutorial helps you to understand the testing RESTful WebserviceClient by mocking the underlying webServer.

Mocking framework(such as Mockito) with RestTemplate, did not fully test the client layer calls and error handling provided, to overcome this problem , MockRestServiceServer will helps you to write complete integrationTests without actually connecting to real server.

MockRestServiceServer comes with DSL syntax to write test scenarios.

PetStoreClient is simple client with placeOrder method which talks to external webServer to place the order.

Write your WebServiceClient testCase compatible as shown below, which helps you to write tests easy
PetStoreClient.java
/**
 * WebService client invokes external webservices using RestTemplate
 *
 * @author ThirupathiReddy Vajjala
 */
@Component
public class PetStoreClient {

    private Logger LOG = LoggerFactory.getLogger(getClass());

    private RestTemplate trustedRestTemplate;

    private String baseUrl;


    @Autowired
    public PetStoreClient(RestTemplate trustedRestTemplate, @Value("${store.base.url}") String baseUrl) {

        this.trustedRestTemplate = trustedRestTemplate;

        this.baseUrl = baseUrl;
    }


    /**
     * Place Order online
     *
     * @param order order
     * @return status
     */
    public Order placeOrder(Order order) {

        try {
            ResponseEntity<Order> responseEntity = trustedRestTemplate.postForEntity(baseUrl + "/store/order", order, Order.class);
            return responseEntity.getBody();
        } catch (HttpClientErrorException e) {
            throw new BadRequestException(e);
        }

    }
}

Instantiate MockRestServiceServer and PetStoreClient as shown below

filename.java
 static PetStoreClient petStoreClient;


    static MockRestServiceServer mockServer;

    @BeforeClass// helps you to create server once for all tests
    public static void setup() {
        RestTemplate restTemplate = new RestTemplate();
        RestGatewaySupport restGatewaySupport = new RestGatewaySupport();
        restGatewaySupport.setRestTemplate(restTemplate);
        mockServer = MockRestServiceServer.createServer(restGatewaySupport);
        petStoreClient = new PetStoreClient(restTemplate, "http://fake.petstore.com");

    }
Test Scenario: Test when server throw 400 BAD_REQUEST exception, PetStoreClient should throw BadRequestException

This testCase verifies the behaviour of placeOrder method when server returns success response

   /**
     * Scenario:  When Server returns bad request, placeOrder should throw BadRequestException
     */
    @Test(expected = BadRequestException.class)
    public void testWhenServerReturnsException() {

        //given:
        mockServer.expect(anything())
                .andRespond(MockRestResponseCreators.withStatus(HttpStatus.BAD_REQUEST));

        //when: invoke placeOrder
        petStoreClient.placeOrder(new Order());

        //then: expect BadRequestException
    }
Test Scenario: When Server returns success response, placeOrder should return Order instance as response

This testCase verifies the behaviour of placeOrder method when server returns bad request

    /**
     * Scenario:  When Server returns success response, placeOrder should return {@link Order} instance as response
     */
  @Test
    public void placeOrderTest() {

        //given:
        mockServer.expect(anything())
                .andRespond(withSuccess(new ClassPathResource("success_response.json"), APPLICATION_JSON));

        //when: invoke placeOrder
        Order order = petStoreClient.placeOrder(new Order());

        //then: expect positive response
        Assert.assertEquals("placed", order.getStatus());
    }

Source code

Complete source code refer Github repository

No comments:

Post a Comment