Pollito Dev
October 15, 2024

Pollito's Opinion on Spring Boot Development 7: Unit tests

Posted on October 15, 2024  •  2 minutes  • 367 words  • Other languages:  Español

Some context

This is the seventh part of the Spring Boot Development blog series.

We already created every component. In this blog we are going to focus on Unit tests. Let’s start!

1. What to test?

When it comes to unit testing , my recommendation is:

2. Mutation testing

What does it mean “Over 60% mutation coverage”? What is mutation testing? Pitest defines it as:

Mutation testing is conceptually quite simple. Faults (or mutations) are automatically seeded into your code, then your tests are run. If your tests fail then the mutation is killed, if your tests pass then the mutation lived. The quality of your tests can be gauged from the percentage of mutations killed.

To get this metric, we use these plugins that we should already have from part 2

Here I leave some ready copy-paste for you. Consider double-checking the latest version.

Under the <plugins> tag:

<plugin>
  <groupId>org.pitest</groupId>
  <artifactId>pitest-maven</artifactId>
  <version>1.17.0</version>
  <executions>
      <execution>
          <id>pit-report</id>
          <phase>test</phase>
          <goals>
              <goal>mutationCoverage</goal>
          </goals>
      </execution>
  </executions>
  <dependencies>
      <dependency>
          <groupId>org.pitest</groupId>
          <artifactId>pitest-junit5-plugin</artifactId>
          <version>1.2.1</version>
      </dependency>
  </dependencies>
  <configuration>
      <targetClasses>
          <param>${project.groupId}.${project.artifactId}.controller.*</param>
          <param>${project.groupId}.${project.artifactId}.service.*</param>
          <param>${project.groupId}.${project.artifactId}.util.*</param>
      </targetClasses>
      <targetTests>
          <param>${project.groupId}.${project.artifactId}.*</param>
      </targetTests>
  </configuration>
</plugin>

3. Generate a report

After creating and making sure your unit tests work, run pitest:mutationCoverage Screenshot2024-10-15162331

You should find in target/pit-reports an index.html, that’s the report. Screenshot2024-10-15173646

Open it in your favourite browser and explore further each class if needed. screencapture-localhost-63342-post-target-pit-reports-index-html-2024-10-15-17_54_48

Next lecture

Pollito’s Opinion on Spring Boot Development 8: JpaRepository and H2

Hey, check me out!

You can find me here