Thursday, August 27, 2009

Mockito and the Builder Pattern for speeding up fixtures in Unit Tests

Mockito is a great mocking library on the JVM and I love the terseness of it and all of the functionality that it offers just like EasyMock.

Problem Description
In one of my projects at my current job, I have been using it to mock out classes in my unit tests of some Freemarker templates. Technically, these are more of integration tests, but since the library that it uses to do the generation of the content is well unit-tested itself, I consider this to be in effect unit tests.

So, I came up with using the Builder pattern in conjunction with mockito to simplify the creation of fixtures. We have a complex object that consists of many other objects and in order to test the templates thoroughly, we needed to constructs many different variants of this object. So using the Agile approach I began creating many of these variants by using helper methods. I kept on refactoring until every hierarchical piece was eventually wrapped up in a separate method.

Just as an example of what I am talking about, I will create an imaginary hierarchical structure that mimics my company's object.

Domain
Let's say that the one object that we are talking about is an object that represents a country.
A country is made up of many states.
A state is made up of many cities.
Let's just keep it simple like this for a moment.
And we will keep track of the population total at each level and the full name of the leader at that post (president, governor, mayor) and the name of the entitity.


Classes

Country.java

package com.mzgubin.mockito_builder_example;

import java.util.List;
import java.util.ArrayList;

public class Country {

private String name;
private String leaderFullName;
private long population = 0;
private List states;

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void setLeaderFullName(String leaderFullname){
this.leaderFullName = leaderFullName;
}

public String getLeaderFullName(){
return leaderFullName;
}

public void setPopulation(long population){
this.population = population;
}

public long getPopulation(){
return population;
}

public void setStates(List states){
this.states = states;
}

public List getStates(){
return states;
}
}


State.java

package com.mzgubin.mockito_builder_example;

import java.util.List;
import java.util.ArrayList;

public class State {

private String name;
private String leaderFullName;
private long population = 0;
private List cities;

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void setLeaderFullName(String leaderFullname){
this.leaderFullName = leaderFullName;
}

public String getLeaderFullName(){
return leaderFullName;
}

public void setPopulation(long population){
this.population = population;
}

public long getPopulation(){
return population;
}

public void setCities(List cities){
this.cities = cities;
}

public List getCities(){
return cities;
}
}


City.java

package com.mzgubin.mockito_builder_example;

public class City {

private String name;
private String leaderFullName;
private long population = 0;

public void setName(String name){
this.name = name;
}

public String getName(){
return name;
}

public void setLeaderFullName(String leaderFullname){
this.leaderFullName = leaderFullName;
}

public String getLeaderFullName(){
return leaderFullName;
}

public void setPopulation(long population){
this.population = population;
}

public long getPopulation(){
return population;
}
}


Mocking
Before using the Builder pattern, I've had to create all of the mock objects manually.
(I am excluding imports etc, just because I want to concentrate on the important code)



package com.mzgubin.mockito_builder_example;

import java.util.List;
import java.util.ArrayList;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class Helper {
public City getMockedCity(){
City city = mock(City.class);
when(city.getName()).thenReturn("New York City");
when(city.getPopulation()).thenReturn(10);
when(city.getLeaderFullName()).thenReturn("Michael Bloomberg");

return city;
}

public State getMockedState(){
List city = new ArrayList();

City city = getMockedCity();
cities.add(city);

State state = mock(State.class);
when(state.getName()).thenReturn("New York");
when(state.getPopulation()).thenReturn(100);
when(state.getLeaderFullName()).thenReturn("David Paterson");
when(state.getCities()).thenReturn(cities);

return state;
}

public Country getMockedCountry(){
State state = getMockedState();
List states = new ArrayList();
states.add(state);
Country country = mock(Country.class)

when(country.getPopulation()).thenReturn(1000);
when(country.getName()).thenReturn("United States");
when(country.getLeaderFullName()).thenReturn("Barrack Obama");
when(country.getStates()).thenReturn(states);
}
}


This is quite an easy example, but if you have things that are more complex, you can imagine, this can become quite tedious to maintain as the code/tests change.

Enter the Builder Pattern
The idea really came from Groovy's builders and I initially wanted to create the builders in Groovy. I did not have much time to investigate using Groovy's builders, so instead I chose to go with Java since I am much more familiar with it.
I created a single Builder per class in the following format:


package com.mzgubin.mockito_builder_example;

import org.apache.log4j.Logger;
import java.util.List;
import java.util.ArrayList;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class CountryBuilder {

private final static Logger log = Logger.getLogger(CountryBuilder.class);

private String name;
private String leaderFullName;
private long population;
private List states;
private Country country;

public CountryBuilder() {
country = mock(Country.class);
}

public CountryBuilder(Country country) {
if (country != null) {
this.country = country;
populateFields(country);
} else {
country = mock(Country.class);
}
}

private void populateFields(Country country) {
this.name= country.getName();
this.leaderFullName = country.getLeaderFullName();
this.population= country.getPopulation();
this.states = country.getStates();
}

public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("Country:\n");
sb.append("name=" + name).append("\n");
sb.append("leaderFullName=" + leaderFullName).append("\n");
sb.append("population=" + population).append("\n");
sb.append("states=" + states.size()).append("\n");

return sb.toString();
}

public Country build(){
if (states == null){
states = new ArrayList();
}

when(country.getName()).thenReturn(name);
when(country.getLeaderFullName()).thenReturn(leaderFullName);
when(country.getPopulation()).thenReturn(population);
when(country.getStates()).thenReturn(states);

dump();

return country;
}

public void dump(){
log.debug(toString());
}

public CountryBuilder name(String name){
this.name = name;
return this;
}

public CountryBuilder leaderFullName(String leaderFullName){
this.leaderFullName = leaderFullName;
return this;
}

public CountryBuilder population(long population){
this.population = population;
return this;
}

public CountryBuilder states(List states){
this.states = states;
}

public CountryBuilder state(State state) throws Exception {
if (this.states == null){
this.states = new ArrayList();
}
this.states.add(state);
return this;
}

public CountryBuilder state(StateBuilder stateBuilder) throws Exception {
this.state(stateBuilder.build());
}
}


And I am not going to list the other two Builder implementations of State and City, as they are nearly identical to this implementation.

And now ladies and gentlemen, viola!
So now we no longer really need to mess with Mockito's implementation too much when we setup the fixtures, except when the Builders themselves need to be augmented.

We can now build a Country fixture object like so:


Country country = new CountryBuilder()
.name("United States")
.fullLeaderName("Barrack Obama")
.population(1000)
.state(
new StateBuilder()
.name("New York")
.fullLeaderName("David Paterson")
.population(100)
.city(
new CityBuilder()
.name("New York City")
.fullLeaderName("Michael Bloomberg")
.population(10)
) // end of city
) // end of state
).build(); // end of country

Now, that is nice and clean!

Maybe next time I will show how to do the same utilizing Groovy's Builder pattern!

Just beware that I did not test this code, but hopefully it will compile. I will try and run it later to make sure it at least compiles. If you find any mistakes, please let me know.

9 comments:

Peter Niederwieser said...

Using builders to create test fixtures is a well-known technique. But why would you need mock objects here?

Maxim Gubin said...

Well in the scenario that I've shown, mock objects are probably not necessary because these are simple POJOs. If you have some really complex logic in the methods (legacy code), then mock objects are a necessity.

JLChoike said...
This comment has been removed by the author.
JLChoike said...

I thought of implementing a Builder to use in conjunction with EasyMock, but did not for the following reasons:

- a Builder would obscured the expressive nature of the EasyMock API (i.e. other developers will immediately know you are working with a mock, and the API clearly states the expectations

- unnecessary overhead (in my opinion), especially since you are simply transferring values from the builder to the mock.

With this Builder pattern, how would you apply it to a situation where mock could throw an exception?

Dave Newton said...

Why not just put the fluent methods into the POJO?

Maxim Gubin said...

Dave,

You are right, I could've easily created separate Builder classes wrapping the original classes, or even better, I could've introduced them into the classes themselves.

The reason I chose to use the Builder pattern as a wrapper around the mocking framework was because I did not have the authority to add the Builder pattern to the original library.

What I wanted was the ability to use predefined values (mocks) in order to test the output of the freemarker templates.

The original code that I was mocking is very messy and has no unit tests. They are not simply POJO to say the least, and are highly coupled. Trying to use a Builder Pattern there would be a nightmare.

I hope that answers your question.

Maxim Gubin said...

JLChoicke,

You are right, it is adding an extra layer, but what it allows you to do is be more productive by creating these complex mocks very easily.

If the underlying code that is being mocked throws an exception, that can be represented by the mock itself.
You can tell the mock to throw an exception at such and such situation.

when(mockedList.get(1)).thenThrow(new RuntimeException());

So, you in effect should be able to cover the exception cases with your tests as well. My tests cover the happy paths, as well as exception cases.

Date Hater said...

Although I love the end result of this (the unit test's setup looks much nicer), it seems really inconvenient and tedious to write these builders yourself. Can you think of a way to automate making these builders?

Alexander Ashitkin said...

another great article :) i've read 2 articles by Maxim one by one and i really impressed by Maxim :) his code style so cool. i just can't figure out why i want to vomit.