A RESTFul Web Service

Filed under: BDD, Cucumber, Test automation, — Tags: CXF, Cucumber-jvm, JSF, JUnit, Jersey, MVC, Model view controller, REST, RESTAssured, RESTFul, Selenium, Soap, Swing,, Swinggui, WebDriver, Wicket — Thomas Sundberg — 2012-11-01

Previous - A Swing application

A RESTFul web service is yet another way to use the model. It doesn't have any user interface and it is expected to be used by third party suppliers. I divide the project using two Maven modules as earlier. One for the production code and one for the verification. The only large difference here is the support class that will connect to the system under test but now has to be adapted for a RESTFul web service instead of any graphical interface. Another difference is of course that there is no GUI and that it is developed using a Jersey servlet instead, but that has little impact on the verification.

The feature is the same:

src/test/resources/se/waymark/rentit/Rent.feature

Feature: Rental cars should be possible to rent to gain revenue to the rental company.

  As an owner of a car rental company
  I want to make cars available for renting
  So I can make money

  Scenario: Find and rent a car
    Given there are 18 cars available for rental
    When I rent one
    Then there will only be 17 cars available for rental

The glue to connect the feature above with Cucumber is the same as earlier:

src/test/java/se/waymark/rentit/RunCukesIT.java

package se.waymark.rentit;


import cucumber.api.junit.Cucumber;
import org.junit.runner.RunWith;

@RunWith(Cucumber.class)
public class RunCukesIT {
}

The steps are identical:

src/test/java/se/waymark/rentit/steps/RentStepdefs.java

package se.waymark.rentit.steps;


import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class RentStepdefs {
    private RentACarSupport rentACarSupport = new RentACarSupport();

    @Given("^there are (\\d+) cars available for rental$")
    public void there_are_cars_available_for_rental(int availableCars) throws Throwable {
        rentACarSupport.createCars(availableCars);
    }

    @When("^I rent one$")
    public void rent_one_car() throws Throwable {
        rentACarSupport.rentACar();
    }

    @Then("^there will only be (\\d+) cars available for rental$")
    public void there_will_be_less_cars_available_for_rental(int expectedAvailableCars) throws Throwable {
        int actualAvailableCars = rentACarSupport.getAvailableNumberOfCars();
        assertThat(actualAvailableCars, is(expectedAvailableCars));
    }
}

The first interesting difference is in the help class. It now deals with REST using RESTAssured rather than a web or Swing application.

src/test/java/se/waymark/rentit/steps/RentACarSupport.java

package se.waymark.rentit.steps;

import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.response.ResponseBody;

import static com.jayway.restassured.RestAssured.expect;

public class RentACarSupport {
    public RentACarSupport() {
        RestAssured.baseURI = "http://localhost";
        RestAssured.port = 8080;
        RestAssured.basePath = "/rentit/rest";
    }

    public void createCars(int availableCars) {
        String path = "/create/" + availableCars;
        expect().statusCode(201).when().post(path);
    }

    public void rentACar() {
        String path = "/rent";
        expect().statusCode(200).when().post(path);
    }

    public int getAvailableNumberOfCars() {
        String path = "/availableCars";
        Response response = expect().statusCode(200).when().get(path);
        ResponseBody body = response.getBody();
        String availableCarsAsString = body.asString();

        return Integer.parseInt(availableCarsAsString);
    }
}

Instead of using Selenium or FEST, I now use RESTAssured for driving the application.

This was the interesting part from a testing point of view.

To execute this, we need a Maven pom that defines the project

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>se.waymark</groupId>
        <artifactId>rest-ws</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <groupId>se.waymark</groupId>
    <artifactId>rest-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.12</version>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <phase>integration-test</phase>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>verify</id>
                        <phase>verify</phase>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.cargo</groupId>
                <artifactId>cargo-maven2-plugin</artifactId>
                <version>1.2.2</version>
                <executions>
                    <execution>
                        <id>start-tomcat</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>stop-tomcat</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <container>
                        <containerId>tomcat7x</containerId>
                        <zipUrlInstaller>
                            <url>http://www.apache.org/dist/tomcat/tomcat-7/v7.0.32/bin/apache-tomcat-7.0.32.zip</url>
                        </zipUrlInstaller>
                        <output>${project.build.directory}/tomcat-logs/container.log</output>
                        <append>false</append>
                        <log>${project.build.directory}/tomcat-logs/cargo.log</log>
                    </container>
                    <configuration>
                        <type>standalone</type>
                        <home>${project.build.directory}/tomcat-home</home>
                        <properties>
                            <cargo.servlet.port>8080</cargo.servlet.port>
                            <cargo.logging>high</cargo.logging>
                        </properties>
                        <deployables>
                            <deployable>
                                <groupId>se.waymark</groupId>
                                <artifactId>rest-main</artifactId>
                                <type>war</type>
                            </deployable>
                        </deployables>
                    </configuration>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <dependencies>
        <dependency>
            <groupId>se.waymark</groupId>
            <artifactId>rest-main</artifactId>
            <version>1.0-SNAPSHOT</version>
            <type>war</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.restassured</groupId>
            <artifactId>rest-assured</artifactId>
            <version>1.6.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-java</artifactId>
            <version>1.1.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>info.cukes</groupId>
            <artifactId>cucumber-junit</artifactId>
            <version>1.1.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

It is similar to the web application versions. It uses Maven fail-safe plugin to execute the test and cargo to deploy the application on a Tomcat.

The RESTFul web service

To be able to build the system, I need to implement the RESTFul web service. This is a trivial RESTFul web service and not really important but included here for completeness. I will therefore skip through it fast. All files needed are included, but I will not go through the details. There are a lot of other people out there who are better sent to describe a RESTFul web service than I am.

File organisation

All files needed for this example are organised like this:

rest-ws
|-- pom.xml
|-- rest-main
|   |-- pom.xml
|   `-- src
|       |-- main
|       |   |-- java
|       |   |   `-- se
|       |   |       `-- waymark
|       |   |           `-- rentit
|       |   |               `-- rest
|       |   |                   `-- RentCar.java
|       |   `-- webapp
|       |       `-- WEB-INF
|       |           `-- web.xml
|       `-- test
|           `-- java
|               `-- se
|                   `-- waymark
|                       `-- rentit
|                           `-- RentCarTest.java
`-- rest-test
    |-- pom.xml
    `-- src
        `-- test
            |-- java
            |   `-- se
            |       `-- waymark
            |           `-- rentit
            |               |-- RunCukesIT.java
            |               `-- steps
            |                   |-- RentACarSupport.java
            |                   `-- RentStepdefs.java
            `-- resources
                `-- se
                    `-- waymark
                        `-- rentit
                            `-- Rent.feature

All test files has already been presented so I will not do that again. The files needed for the RESTFul web service looks like this:

Parent pom

A parent pom is used to connect the two sub modules. It is defined as:

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>se.waymark</groupId>
    <artifactId>rest-ws</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>pom</packaging>
    <modules>
        <module>rest-main</module>
        <module>rest-test</module>
    </modules>
</project>

Main application pom

rest-main/pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>se.waymark</groupId>
        <artifactId>rest-ws</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <groupId>se.waymark</groupId>
    <artifactId>rest-main</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <build>
        <finalName>rentit</finalName>
    </build>
    <dependencies>
        <dependency>
            <groupId>se.waymark.educational</groupId>
            <artifactId>model</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.9</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Nothing interesting here. It builds a web application and gives it the final name rentit.

The web service

The web service is implemented as:

src/main/java/se/waymark/rentit/rest/RentCar.java

package se.waymark.rentit.rest;

import se.waymark.rentit.model.dao.CarDAO;
import se.waymark.rentit.model.dao.InMemoryCarDAO;
import se.waymark.rentit.model.entiy.Car;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/")
public class RentCar {
    private static CarDAO carDAO = new InMemoryCarDAO();

    @POST
    @Path("/create/{param}")
    public Response createCars(@PathParam("param") Integer numberOfCars) {
        for (int i = 0; i < numberOfCars; i++) {
            Car car = new Car();
            carDAO.add(car);
        }

        return Response.status(201).build();
    }

    @POST
    @Path("/rent")
    public Response rentCar() {
        Car car = carDAO.findAvailableCar();
        car.rent();

        return Response.status(200).build();
    }

    @GET
    @Path("/availableCars")
    public Response getAvailableCars() {
        int availableCars = carDAO.getNumberOfAvailableCars();

        return Response.status(200).entity("" + availableCars).build();
    }
}

Web application

The service is wired to the Jersey servlet in web.xml:

src/main/webapp/WEB-INF/web.xml

<web-app id="WebApp_ID" version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>
    <servlet>
        <servlet-name>REST-servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>se.waymark.rentit.rest</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>REST-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>
</web-app>

Unit test

I wired the application together using this test:

src/test/java/se/waymark/rentit/RentCarTest.java

package se.waymark.rentit;

import org.junit.Test;
import se.waymark.rentit.rest.RentCar;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class RentCarTest {
    @Test
    public void shouldRentACar() {
        int initialNumberOfCars = 43;

        RentCar rentCar = new RentCar();
        rentCar.createCars(initialNumberOfCars);

        rentCar.rentCar();

        int oneRentedCar = 1;
        Integer expected = initialNumberOfCars - oneRentedCar;

        String actualString = (String) rentCar.getAvailableCars().getEntity();

        Integer actual = Integer.parseInt(actualString);

        assertThat(actual, is(expected));
    }
}

Conclusion

A simple RESTFul web service can be added on top of the model without changing the defined behaviour. This is Behaviour Driven Development. You define the behaviour you want. Implement it. Add an interface if it is needed but don't change the behaviour if you don't have to. Next exercise is to use the same behaviour but connect to it from a SOAP based web service. I will use a CXF based SOAP web service this time.

Next - A SOAP web service



(less...)

Pages

About
Events
Why

Categories

Agile
Automation
BDD
Clean code
Continuous delivery
Continuous deployment
Continuous integration
Cucumber
Culture
Design
Executable specification
Gradle
Guice
J2EE
JUnit
Java
Linux
Load testing
Maven
Mockito
Pair programming
PicoContainer
Programming
Public speaking
Quality
Recruiting
Requirements
Scala
Selenium
Software craftsmanship
Software development
Spring
TDD
Teaching
Technical debt
Test automation
Tools
Web
Windows
eXtreme Programming

Authors

Thomas Sundberg
Adrian Bolboaca

Archives

Meta

rss RSS