Boost Spring Boot Code Quality: Automated Unit Tests, Cobertura Coverage, and Jenkins CI
This guide explains how to raise Spring Boot code quality to near‑zero defects by writing comprehensive unit tests for Service, DAO, and Controller layers, integrating the Cobertura plugin for detailed coverage metrics, and automating the process with Jenkins for continuous integration.
Introduction
Before a system goes live, developers perform self‑testing and QA runs test cases, yet production failures still occur; achieving zero‑defect releases requires more than code reviews and functional tests. Measuring code coverage—statement, branch, and path coverage—helps raise code quality to the next level.
Code Quality and Unit Testing
High‑quality code should handle normal and exceptional scenarios (roughly a 30% : 70% split). Unit tests that cover method, statement, condition, and branch coverage provide a quantitative gauge of test completeness.
Adding Unit‑Test Dependencies to a Spring Boot Project
JUnit – core Java unit‑testing framework
Spring Test & Spring Boot Test – integration testing utilities for Spring Boot
AssertJ – fluent assertion library
Hamcrest – matcher library
Mockito – mock object framework
JsonPath – JSON‑XPath support
JSONassert – JSON assertion library
Include spring-boot-starter-test in the pom.xml to bring in these libraries.
Service/DAO Layer Unit Test Example
@SpringBootTest(classes = OpHuaweiAgentApplication.class)
@Slf4j
public class VmServiceTest {
private ObjectMapper mapper = new ObjectMapper();
private static final String JSON_CREATE_VM_REQUEST = "/vm/createVmReq.json";
@Autowired
private VmService vmService;
@Before
public void setUp() throws Exception {
// Prepare test data
}
@Test
public void create() throws Exception {
String createBody = getResource(JSON_CREATE_VM_REQUEST);
JSONObject body = JSONObject.parseObject(createBody);
HwTokenWrapper token = getDomainToken();
String projectId = token.getToken().getProject().getId();
CreateJobRespDto respDto = vmService.create(token.getId(), projectId, body);
assertTrue(respDto.getJobId() != null);
log.debug("create vm job created successfully, jobId:{}", respDto);
}
@After
public void cleanUp() throws Exception {
// Clean test data
}
}Controller API Unit Test with MockMvc
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = OpHuaweiAgentApplication.class)
@WebAppConfiguration
@Slf4j
public class OrderManageControllerTest extends AbstractTest {
private static final String GENERATE_ORDERID_API_URL = "/rest/xxxxxxxxx";
private static final String JSON_AUTH_TOKEN_REQ = "/api/order/authTokenReq.json";
@Autowired
private WebApplicationContext context;
private MockMvc mvc;
@Before
public void setUp() {
// Prepare test data
this.mvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
@Test
public void generateOrderIdTest() throws Exception {
JSONObject jsonObject = JSONObject.parseObject(getResource(JSON_AUTH_TOKEN_REQ));
MockHttpServletRequestBuilder builder = post(GENERATE_ORDERID_API_URL)
.header("X-Auth-Token", jsonObject.getString("token"));
MvcResult result = mvc.perform(builder).andReturn();
assertEquals(HttpStatus.OK.value(), result.getResponse().getStatus());
}
@After
public void cleanUp() throws Exception {
// Clean test data
}
}Integrating Cobertura for Coverage Measurement
Cobertura is an open‑source tool that instruments bytecode during test execution and produces XML/HTML reports showing line, branch, and condition coverage.
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.7</version>
<configuration>
<formats>
<format>xml</format>
<format>html</format>
</formats>
<maxmem>256m</maxmem>
<instrumentation>
<excludes>
<exclude>com/alertavert/**/*Configuration.class</exclude>
<exclude>com/alertavert/**/*Application.class</exclude>
</excludes>
</instrumentation>
<check>
<totalLineRate>70</totalLineRate>
</check>
</configuration>
</plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
<version>3.0.1</version>
</plugin>
</plugins>
</build>Generating the Coverage Report
Run the Maven command mvn cobertura:cobertura in the project root. The plugin creates target/site/cobertura containing index.html (HTML report) and coverage.xml. Opening the HTML file shows line, branch, and method coverage percentages.
Jenkins Integration
Install the Cobertura plugin in Jenkins.
Configure the Maven build step to run clean cobertura:cobertura package.
Add a post‑build action “Publish Cobertura Coverage Report”.
Set the report path to **/target/site/cobertura/coverage.xml.
Re‑build the job; Jenkins will display the coverage trend and detailed metrics.
Conclusion
The article demonstrates a complete workflow: writing unit tests for all Spring Boot layers, measuring coverage with Cobertura, and automating the process in Jenkins to obtain continuous, quantitative feedback on code quality, helping teams move toward zero‑defect releases.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
