Mutation testing cover image

Mutation testing

Ronald van Eede • February 19, 2016 • 4 min read

Development Java Testing

This is the original article, you can also find this article on my employer’s website.

When you write code you also write tests to prove that your code works, right? But how do you know your tests are correct? How to test your tests? This is where Mutation Testing comes in. How does that work?

The concept of mutation testing is simple, when you run your tests faults are automatically seeded into your code. If your tests fail the mutation is killed, are your tests still green? Then the mutation lived. So you can measure the quality of your tests by the amount of mutation that are killed. So you run your unit tests against automatically modified versions of your code. When the code changes different results will be produced and your tests should fail. Why?

Why do you want to do this? We can measure quality with test coverage, right? This is only true up to a certain level. There is no guarantee that your tests can actually detect faults. Test coverage only measures which code is executed. How?

So how do we do this with Java? There are some mutation testing systems for Java but the most widely used one is PIT.

All you have to do to get started is to add a build plugin in your pom.xml and add some configuration for the classes you want to target and the tests that you want to use:

1<plugin>
2 <groupId>org.pitest</groupId>
3 <artifactId>pitest-maven</artifactId>
4 <version>1.1.6</version>
5 <configuration>
6 <targetClasses>
7 <param>com.vaneede.ronald.pittest.factory*</param>
8 </targetClasses>
9 <targetTests>
10 <param>com.vaneede.ronald.pittest.factory*</param>
11 </targetTests>
12 </configuration>
13</plugin>

Now you can use the mvn org.pitest:pitest-maven:mutationCoverage command to run the mutation tests, but make sure you have a green unit test suite first, because PIT needs that. there is also a plugin available for IntelliJ and Eclipse.

To give it a try you can create a small Java project Create a Movie.java file with this content:

1package com.vaneede.ronald.pittest.entity;
2 
3public class Movie {
4 private final String id;
5 private final String title;
6 private final String director;
7 
8 public Movie(String id, String title, String director) {
9 this.id = id;
10 this.title = title;
11 this.director = director;
12 }
13 
14 public String getId() {
15 return id;
16 }
17 
18 public String getTitle() {
19 return title;
20 }
21 
22 public String getDirector() {
23 return director;
24 }
25}

And a MovieFactory.java file:

1package com.vaneede.ronald.pittest.factory;
2 
3import com.vaneede.ronald.pittest.entity.Movie;
4import java.util.UUID;
5 
6public class MovieFactory {
7 private static final int MIN_LENGTH = 3;
8 
9 public Movie create(final String title, final String director) {
10 if (title == null) {
11 throw new IllegalArgumentException("title must be set");
12 }
13 if (title.length() <= MIN_LENGTH) {
14 throw new IllegalArgumentException("title must have a minimal length of " + MIN_LENGTH);
15 }
16 if (director == null) {
17 throw new IllegalArgumentException("director must be set");
18 }
19 
20 return new Movie(UUID.randomUUID().toString().toUpperCase(), title, director);
21 }
22}

And a test class, MovieFactroyTest:

1package com.vaneede.ronald.pitest.factory;
2 
3import com.vaneede.ronald.pittest.entity.Movie;
4import com.vaneede.ronald.pittest.factory.MovieFactory;
5import org.junit.Test;
6 
7import static org.hamcrest.MatcherAssert.assertThat;
8import static org.hamcrest.Matchers.equalTo;
9import static org.hamcrest.Matchers.isEmptyOrNullString;
10import static org.hamcrest.Matchers.not;
11import static org.hamcrest.Matchers.notNullValue;
12 
13public class MovieFactoryTest {
14 private static final String TITLE = "Pulp Fiction";
15 private static final String DIRECTOR = "Quentin Tarantino";
16 
17 private final MovieFactory movieFactory = new MovieFactory();
18 
19 @Test
20 public void shouldCreateMovie() throws Exception {
21 final Movie movie = movieFactory.create(TITLE, DIRECTOR);
22 assertThat(movie, notNullValue());
23 assertThat(movie.getTitle(), equalTo(TITLE));
24 assertThat(movie.getDirector(), equalTo(DIRECTOR));
25 assertThat(movie.getId(), not(isEmptyOrNullString()));
26 }
27 
28 @Test(expected = IllegalArgumentException.class)
29 public void shouldFailCreateMovieWithNoTitleGiven() throws Exception {
30 movieFactory.create(null, DIRECTOR);
31 }
32 
33 @Test(expected = IllegalArgumentException.class)
34 public void shouldFailCreateMovieWithNoDirectorGiven() throws Exception {
35 movieFactory.create(TITLE, null);
36 }
37 
38 @Test(expected = IllegalArgumentException.class)
39 public void shouldFailCreateMovieWithTooShortTitleGiven() throws Exception {
40 movieFactory.create("pf", DIRECTOR);
41 }
42}

When you run the tests with coverage you will see that all the code in the MovieFactory class is covered by the tests. So we tested everything, right? Not entirely. Let's run PIT.
PIT will run the tests again but it will make small changes to the code. It does this in-memory so it's fast and it does not change your actual code. It changes things like == to !=, != to ==, <= to <, return true instead of false, or false instead of true etcetera.

1================================================================================
2- Statistics
3================================================================================
4>> Generated 8 mutations Killed 7 (88%)
5>> Ran 11 tests (1.38 tests per mutation)

So it looks like our tests killed 7 mutations, but 1 survived. Can you already find it?
Let's continue with the report summary:

1================================================================================
2- Mutators
3================================================================================
4> org.pitest.mutationtest.engine.gregor.mutators.ConditionalsBoundaryMutator
5>> Generated 1 Killed 0 (0%)
6> KILLED 0 SURVIVED 1 TIMED_OUT 0 NON_VIABLE 0
7> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
8> NO_COVERAGE 0
9--------------------------------------------------------------------------------
10> org.pitest.mutationtest.engine.gregor.mutators.ReturnValsMutator
11>> Generated 4 Killed 4 (100%)
12> KILLED 4 SURVIVED 0 TIMED_OUT 0 NON_VIABLE 0
13> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
14> NO_COVERAGE 0
15--------------------------------------------------------------------------------
16> org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator
17>> Generated 3 Killed 3 (100%)
18> KILLED 3 SURVIVED 0 TIMED_OUT 0 NON_VIABLE 0
19> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
20> NO_COVERAGE 0
21--------------------------------------------------------------------------------

Mutators

So PIT used three different kind of mutators: ConditionalsBoundaryMutator, ReturnValsMutator and NegateConditionalsMutator.
The ConditionalsBoundaryMutator changes < to <=, <= to <, > to >= and >= to >.
The ReturnValsMutator changes the return values of your methods, so if your method normally returns true it is mutated to return false instead. Or it the method normally returns an Object it will return null.
The NegateConditionalsMutator changes conditional statements, so it will change == to !=, != to ==, <= to >, >= to <, < to >= and > to <=. Besides these three mutators there are a total of 13 possible mutators, 7 of them are enabled by default, the others have to be enabled explicitly.
As you can see in the report above only 3 out of the 7 that are enabled by default where used, that is because the others where not applicable for the example code.So we have 1 mutation that survived, let's take a deeper look at that one. PIT generated a nice HTML report in the target directory so we can open that in the browser.

Light green shows line coverage.
Dark green shows mutation coverage.
Light pink show lack of line coverage.
Dark pink shows lack of mutation coverage.

In the report you can see that there is a problem on line 14. PIT tested that line with a NegateConditionalsMutator and a ConditionalsBoundaryMutator mutator. As you can see in the list of Mutations the ConditionalsBoundaryMutator mutation caused a test to fail, so the mutant survived.
In this case this is because we only test for a movie title shorter than 3 characters but not for a title of exactly 3 characters. So by including mutation into our project we discovered that we where missing a test.
This is only one small example, there are a lot more mutators that can be used, like the VoidMethodCalls mutator that removed calls to void methods or the MathMutator that changes calculations in your code.