Open sourcing my workshop on WireMock

For those of you that want to jump to the good stuff directly, you can find the workshop slides, exercises and everything related here.

A couple of weeks ago I was given the opportunity to deliver another workshop before TestNet, the Dutch software testing community, as part of their fall conference. Half a year ago, I did a similar workshop for their spring conference. That workshop was on RESTful API testing using REST Assured, which I decided to make open source a little later on. I’ve received some positive feedback on that, so why not do it again?

This time, the conference was centered around test automation. The subject of my workshop this time was closely related to the main theme: stubbing test environment dependencies using WireMock.

The title slide for my workshop

Delivery
As with most workshops that day, mine was set in a classroom-style space. I had somewhere between 15 and 20 participants, which I think is pretty much the ideal group size for a hands-on workshop that involves writing code. Not so many that I can’t give proper attention to all questions asked, but not a group so small you start to doubt whether the upfront investment has been worth it. As those of you who have prepared and delivered workshops before, you know that preparing them takes a lot of time. Spending all those hours and then only having two people turn up, one of whom is a coworker and the other one seems a little lost, is a bit of a bummer. Fortunately, this wasn’t the case for me, at least not this time..

The levels of experience of the participants (semi-pro tip: know your audience) ranged from people having some prior experience with stub and mock development to people that had never in their life written a single line of code before. An interesting mix, to say the least!

Workshop contents
As said, the main subject of the workshop was WireMock. I started out by telling people a little about the difficulties with regards to keeping test environments up and running and properly configured in these times of parallel development, Continuous Delivery and Testing and distributed applications. I then introduced WireMock, which I’ve done here on this site before as well. Then came four cycles of me presenting a WireMock feature, followed by exercises where the participants could try this feature out for themselves. I chose to highlight the following WireMock features in the workshop:

  • Writing a first, basic stub
  • Request matching options
  • Fault simulation
  • Creating stateful mocks

For each set of exercises, I prepared REST Assured tests that the participants could run to see if their stub implementation was correct. Call it test driven stub development if you like. This approach worked remarkably well, it definitely saved me a lot of time answering questions in the ‘is this correct?’ vein. Test green = stub good, test red = stub needs improvement. It doesn’t get any clearer than that.

Here’s an example of an exercise and the test that determines the correctness of the solution:

public void setupStubExercise101() {

	/************************************************
	 * Create a stub that listens at path
	 * /exercise101
	 * and responds to all GET requests with HTTP status code 200
	 ************************************************/
}

@Test
public void testExercise101() {
        
    wme.setupStubExercise101();
	         
    given().
    when().
        get("http://localhost:9876/exercise101").
    then().
        assertThat().
        statusCode(200);
}

How it turned out
Fine, I think. Time flew by and I didn’t experience any major faults, missing or incorrect slides or things like that. The experience I’m slowly gathering by doing this more often is starting to pay off, I think. I received almost exclusively positive feedback on the workshop, so I’m a happy guy. Also, everybody seemed to have learned at least something new and enjoyed the process too, no matter whether they had prior stubbing or even programming experience or not, and that has been the most important result of the morning to me. I’m looking forward to the next opportunity for delivering this workshop.

Having said that…
All workshop contents, that’s:

  • The complete set of slides
  • All workshop exercises and their answers
  • Matching REST Assured tests to verify the stubs created

can be found on my GitHub page. As with the previous workshop I’ve published in this manner, feel free to download, adapt, extend and then deliver the workshop to your liking. I look forward to hearing your experiences.

And in case you’re interested in following a WireMock workshop, but do not want to deliver this yourself, don’t hesitate to contact me. I’ll be happy to discuss options. Also, this workshop can easily be combined with a workshop on REST Assured for a full day of API testing and stubbing goodness.

(De)serializing POJOs in REST Assured

In this post, I’d like to demonstrate how you can leverage the ability of REST Assured to (de-)serialize Plain Old Java Objects (better known as POJOs) for more powerful testing.

As an example, we’ll use the following POJO representing a car and some of its properties:

public class Car {
	
	String make;
	String model;
	int year;
	
	public Car() {		
	}
	
	public Car(String make, String model, int year) {
		
		this.make = make;
		this.model = model;
		this.year = year;
	}
	
	public String getMake() {
		return this.make;
	}

	public void setMake(String make) {
		this.make = make;
	}
	
	public String toString() {
		return "My car is a " + this.year + " " + this.make + " " + this.model;
	}
}

Please note that I’ve removed the getters and setters for the other properties for brevity. Now, let’s create an instance of the car:

Car myCar = new Car("Aston Martin","DB9",2004);

Say we want to transmit the information stored in this object instance to a RESTful API, without having to map each individual property of our car to a corresponding field in the request. REST Assured supports this by allowing you to serialize the myCar object instance as follows:

@Test
public void testCarSerialization() {
				
	given().
		contentType("application/json").
		body(myCar).
	when().
		post("http://localhost:9876/carstub").
	then().
		assertThat().
		body(equalTo("Car has been stored"));
}

So, all you have to do is pass the object using body(). REST Assured will automatically translate this to the following request body:

{
    "make": "Aston Martin",
    "model": "DB9",
    "year": 2004
}

Neat, right? In this example, we serialized the car object to a JSON request, but REST Assured also allows you to serialize it to XML or HTML. Additionally, you can create custom object mappings as well. See this page in the REST Assured documentation for more information.

REST Assured also supports deserialization, meaning that we can easily transform a suitably formatted API response to a POJO instance:

@Test
public void testCarDeserialization() {
		
	Car myDeserializedCar = get("http://localhost:9876/carstub").as(Car.class);
		
	System.out.println(myDeserializedCar.toString());
	
	Assert.assertEquals("Check the car make", myDeserializedCar.getMake(), "Aston Martin");		
}

Note that http://localhost:9876/carstub points to a WireMock stub I’ve created to illustrate this example. The fact that our assertion is passing and that the console shows the following output when running the test tells us that deserialization has been successful:

My car is a 2004 Aston Martin DB9

You can download a Maven project containing all of the code I’ve used in the examples in this blog post here.

How (not) to test RESTful APIs with Selenium WebDriver

I’ve seen the question of how to do RESTful API testing with Selenium WebDriver come up a lot in various places. I’ve seen it mainly on LinkedIn, but a couple of weeks ago I was asked this question in person as well. So, as your ever helpful consultant, I thought I’d be a good idea to show you how it’s done.

First, let’s create a new browser driver object. For the sake of simplicity, I’ll use Firefox, because it doesn’t require setting up a separate driver. And yes, I know implicit waits aren’t the best waiting strategy, but I didn’t feel like writing an ExpectedCondition.

driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Now, instead of browsing to a web page, we’ll simply browse to the RESTful API endpoint for which we want to check the response. I’ll use api.zippopotamus.us as an example here to look up some data for the US zip code 90210:

driver.get("http://api.zippopotam.us/us/90210");

This gives us the following output:

Response from the zippopotam.us API in JSON format

Let’s grab the text we see on screen and convert it to a JSON object (using the org.json package):

WebElement element = driver.findElement(By.xpath("//pre"));
JSONObject jsonObject = new JSONObject(element.getText());

Now that we have a JSON object containing the API response, we can extract specific elements and check their value:

String valueToCheck = jsonObject.get("country").toString();
Assert.assertEquals(valueToCheck, "United States");

As a final step, throw everything away, never do this again and please forget everything you’ve seen so far in this post. Selenium is not an API testing tool. It has never been, and it will never be. So please don’t try and force it to be.

Please stick to simulating UI interaction when using Selenium and use a dedicated, fit for purpose tool for API testing. As an example, REST Assured can perform the exact same check as the above. With a single line of code. Which is far better readable to boot:

@Test
public void doRestTestProperly() {
		
	given().
	when().
		get("http://api.zippopotam.us/us/90210").
	then().
		assertThat().
		body("country", equalTo("United States"));
}

So, here’s to hoping I did my part in exterminating questions that feature ‘Selenium’ and ‘API testing’ in the same sentence.