Spring Boot Testing with Gradle: Using JUnit and Mockito

Testing is a critical part of any software development process, and Spring Boot makes it easy to write tests using JUnit and Mockito. In this tutorial, we'll walk you through setting up a Spring Boot project with Gradle and show you how to write and run tests using JUnit and Mockito.

Prerequisites

  • Java 17 or later installed
  • Gradle installed
  • IDE (IntelliJ IDEA, Eclipse, etc.)

Step-by-Step Guide

Step 1: Setting Up the Project

  1. Create a new directory for your project and navigate into it:
mkdir spring-boot-testing
cd spring-boot-testing
  1. Initialize a new Gradle project:
gradle init --type java-application
  1. Update the build.gradle file with the necessary dependencies:

build.gradle

plugins {
    id 'org.springframework.boot' version '3.2.0'
    id 'io.spring.dependency-management' version '1.1.0'
    id 'java'
}

group = 'com.example'
version = '1.0.0'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.mockito:mockito-core:5.1.1'
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.0'
}

test {
    useJUnitPlatform()
}

Explanation:

  • Plugins Section: Adds Spring Boot, dependency management, and Java plugins.
  • Group and Version: Defines the project group and version.
  • Source Compatibility: Sets Java version compatibility.
  • Repositories: Configures Maven Central as the repository.
  • Dependencies: Adds necessary dependencies for Spring Boot, JUnit, and Mockito.

Step 2: Creating a Simple Spring Boot Application

  1. Create a com.example.demo package in src/main/java and add a DemoApplication class:

src/main/java/com/example/demo/DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Explanation:

  • SpringBootApplication: Annotation to mark this class as the main entry point for the Spring Boot application.
  • SpringApplication.run: Method to launch the Spring Boot application.
  1. Add a simple GreetingService class that we will test:

src/main/java/com/example/demo/GreetingService.java

package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class GreetingService {

    public String greet(String name) {
        return "Hello, " + name;
    }
}

Explanation:

  • Service Annotation: Marks this class as a Spring service component.
  • greet Method: A simple method to return a greeting message.
  1. Add a GreetingController class to expose an endpoint:

src/main/java/com/example/demo/GreetingController.java

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    @Autowired
    private GreetingService greetingService;

    @GetMapping("/greet")
    public String greet(@RequestParam String name) {
        return greetingService.greet(name);
    }
}

Explanation:

  • RestController Annotation: Marks this class as a REST controller.
  • Autowired Annotation: Injects the GreetingService into the controller.
  • GetMapping Annotation: Maps HTTP GET requests to the /greet endpoint.
  • greet Method: Calls the service method to get the greeting message.

Step 3: Writing Tests with JUnit and Mockito

  1. Create a com.example.demo package in src/test/java and add a GreetingServiceTest class:

src/test/java/com/example/demo/GreetingServiceTest.java

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertEquals;

@ExtendWith(MockitoExtension.class)
public class GreetingServiceTest {

    @InjectMocks
    private GreetingService greetingService;

    @Test
    public void testGreet() {
        String result = greetingService.greet("World");
        assertEquals("Hello, World", result);
    }
}

Explanation:

  • ExtendWith Annotation: Integrates Mockito with JUnit 5.
  • InjectMocks Annotation: Creates an instance of GreetingService and injects any dependencies.
  • testGreet Method: Tests the greet method of GreetingService.
  1. Add a GreetingControllerTest class to test the controller:

src/test/java/com/example/demo/GreetingControllerTest.java

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;

@ExtendWith(MockitoExtension.class)
@WebMvcTest(GreetingController.class)
public class GreetingControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Mock
    private GreetingService greetingService;

    @InjectMocks
    private GreetingController greetingController;

    @Test
    public void testGreetEndpoint() throws Exception {
        when(greetingService.greet("World")).thenReturn("Hello, World");

        mockMvc.perform(get("/greet").param("name", "World"))
               .andExpect(status().isOk())
               .andExpect(content().string("Hello, World"));
    }
}

Explanation:

  • ExtendWith and WebMvcTest Annotations: Set up Mockito and Spring MVC Test.
  • Mock Annotation: Mocks the GreetingService.
  • InjectMocks Annotation: Injects the mock service into the GreetingController.
  • MockMvc: Mocks the MVC environment for testing controllers.
  • testGreetEndpoint Method: Tests the /greet endpoint with a mock service.

Step 4: Running the Tests

To run the tests, execute the following command in the project root directory:

./gradlew test

Conclusion

In this tutorial, we set up a Spring Boot project with Gradle and demonstrated how to write tests using JUnit and Mockito. We covered testing both the service layer and the web layer. This approach helps ensure your application logic and endpoints are working correctly.

For more information and in-depth guides, visit the Spring Boot documentation and the JUnit 5 documentation.

Comments