🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Prerequisites
- Java 17 or later installed
- Gradle installed
- IDE (IntelliJ IDEA, Eclipse, etc.)
Step-by-Step Guide
Step 1: Setting Up the Project
- Create a new directory for your project and navigate into it:
mkdir spring-boot-testing
cd spring-boot-testing
- Initialize a new Gradle project:
gradle init --type java-application
- Update the
build.gradlefile 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
- Create a
com.example.demopackage insrc/main/javaand add aDemoApplicationclass:
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.
- Add a simple
GreetingServiceclass 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.
- Add a
GreetingControllerclass 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
GreetingServiceinto the controller. - GetMapping Annotation: Maps HTTP GET requests to the
/greetendpoint. - greet Method: Calls the service method to get the greeting message.
Step 3: Writing Tests with JUnit and Mockito
- Create a
com.example.demopackage insrc/test/javaand add aGreetingServiceTestclass:
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
GreetingServiceand injects any dependencies. - testGreet Method: Tests the
greetmethod ofGreetingService.
- Add a
GreetingControllerTestclass 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
/greetendpoint 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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment