Introdução
Neste projeto, você aprenderá como criar testes unitários para um Módulo de Gerenciamento de Estudantes usando JUnit 5 e Mockito. O projeto inclui duas tarefas principais: criar testes para a classe StudentServiceImpl e criar testes para a classe StudentController.
🎯 Tarefas
Neste projeto, você aprenderá:
- Como criar um arquivo
ServiceTests.javapara testar a classeStudentServiceImplusando JUnit 5 - Como criar um arquivo
ControllerTests.javapara testar a classeStudentControllerusando JUnit 5 e Mockito - Como usar os recursos de teste do Spring Boot, como
@SpringBootTeste@MockBean, para carregar os componentes necessários e criar mocks para testes - Como escrever casos de teste para verificar a funcionalidade dos métodos
queryStudents(),insertStudent()edeleteStudent()na classeStudentServiceImpl - Como escrever casos de teste para verificar a funcionalidade dos métodos
getStudents(),getStudent()emodifyStudent()na classeStudentController
🏆 Conquistas
Após concluir este projeto, você será capaz de:
- Configurar testes unitários para uma aplicação Spring Boot usando JUnit 5 e Mockito
- Usar os recursos de teste do Spring Boot para carregar os componentes necessários e criar mocks para testes
- Escrever casos de teste eficazes para garantir a correção das implementações da camada de serviço e controlador
- Usar asserções para verificar o comportamento esperado dos métodos testados
Criar o arquivo ServiceTests.java
Nesta etapa, você aprenderá como criar o arquivo ServiceTests.java para testar a classe StudentServiceImpl usando JUnit 5.
- Abra sua IDE e navegue até o diretório
/test/java/org/labex/springboottestingem seu projeto. - Crie um novo arquivo Java chamado
ServiceTests.java. - No arquivo
ServiceTests.java, adicione o seguinte código:
package org.labex.springboottesting;
import org.junit.jupiter.api.Test;
import org.labex.springboottesting.service.StudentServiceImpl;
import org.labex.springboottesting.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(classes = StudentServiceImpl.class)
class ServiceTests {
@Autowired
private StudentServiceImpl service;
@Test
void testQueryStudents() {
// Testing the queryStudents() method of the service to ensure correct data retrieval.
List<Student> result = service.queryStudents();
// Asserting that the size of the returned list matches the expected size.
assertEquals(3, result.size());
}
@Test
void testInsertStudent() {
// Creating a sample student object to insert.
Student student = new Student("1", "test", 18, "male");
// Testing the insertStudent() method of the service to ensure successful insertion.
Boolean result = service.insertStudent(student);
// Asserting that the insertion operation was successful.
assertTrue(result);
}
@Test
void testDeleteStudent() {
// Testing the deleteStudent() method of the service to ensure successful deletion.
Boolean result = service.deleteStudent("20191001");
// Asserting that the deletion operation was successful.
assertTrue(result);
}
}
A classe ServiceTests é anotada com @SpringBootTest(classes = StudentServiceImpl.class) para carregar a classe de implementação StudentServiceImpl na classe de teste. A classe contém três métodos de teste:
testQueryStudents(): Testa o métodoqueryStudents()da interfaceIStudentServicepara garantir que a lista de estudantes retornada tenha o tamanho esperado.testInsertStudent(): Testa o métodoinsertStudent()da interfaceIStudentServicepara garantir que a operação de inserção do estudante seja bem-sucedida.testDeleteStudent(): Testa o métododeleteStudent()da interfaceIStudentServicepara garantir que a operação de exclusão do estudante seja bem-sucedida.
Criar o arquivo ControllerTests.java
Nesta etapa, você aprenderá como criar o arquivo ControllerTests.java para testar a classe StudentController usando o framework de teste Mockito.
- Abra sua IDE e navegue até o diretório
/test/java/org/labex/springboottestingem seu projeto. - Crie um novo arquivo Java chamado
ControllerTests.java. - No arquivo
ControllerTests.java, adicione o seguinte código:
package org.labex.springboottesting;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.labex.springboottesting.dao.IStudentDAO;
import org.labex.springboottesting.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import java.util.ArrayList;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest // Loading the Spring Boot application context.
@EnableWebMvc // Enables Spring Web MVC features.
@AutoConfigureMockMvc // Configures the MockMvc instance.
class ControllerTests {
@Autowired
private MockMvc mockMvc; // Autowires the MockMvc instance for simulating HTTP requests.
private ObjectMapper objectMapper; // ObjectMapper for JSON conversion.
@MockBean // MockBean annotation to create a mock for IStudentDAO.
private IStudentDAO studentDAO;
@BeforeEach
void setUp() {
// Initializing ObjectMapper to convert objects to JSON and vice versa.
this.objectMapper = new ObjectMapper();
}
@Test
void testGetStudents() throws Exception {
// Creating sample students.
Student s1 = new Student("20191001", "John", 18, "Male");
Student s2 = new Student("20191069", "Lily", 19, "Female");
// Creating a list of students and adding sample students to it.
ArrayList<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
// Mocking the behavior of studentDAO to return the list of students when findStudentAll() is called.
when(studentDAO.findStudentAll()).thenReturn(list);
// Performing a GET request to retrieve all students and validating the response.
this.mockMvc.perform(get("/api/v2/students")
.accept("application/json; charset=UTF-8")) // Sets the accept header to specify the expected response type.
.andDo(print()) // Prints request and response details.
.andExpect(status().isOk()) // Verifies that the response status is OK (200).
.andReturn(); // Returns the MvcResult object for further assertions.
}
@Test
void testGetStudent() throws Exception {
// Creating a sample student.
Student s1 = new Student("20191001", "John", 18, "Male");
// Mocking the behavior of studentDAO to return the sample student when findStudentById() is called with "20191001".
when(studentDAO.findStudentById("20191001")).thenReturn(s1);
// Performing a GET request to retrieve a specific student by ID and validating the response.
this.mockMvc.perform(get("/api/v2/student/20191001")
.accept("application/json; charset=UTF-8"))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
@Test
void testModifyStudent() throws Exception {
// Creating a sample student.
Student s1 = new Student("20191001", "John", 18, "Male");
// Converting the sample student to JSON format.
String content = objectMapper.writeValueAsString(s1);
// Mocking the behavior of studentDAO to return true when updateStudent() is called with any student object.
when(studentDAO.updateStudent(any())).thenReturn(true);
// Performing a PUT request to modify a student and validating the response.
this.mockMvc.perform(put("/api/v2/student")
.content(content)
.contentType(MediaType.APPLICATION_JSON)
.accept("application/json; charset=UTF-8"))
.andDo(print())
.andExpect(status().isOk())
.andReturn();
}
}
A classe ControllerTests é anotada com @SpringBootTest para carregar o contexto da aplicação Spring Boot, @EnableWebMvc para habilitar os recursos do Spring Web MVC e @AutoConfigureMockMvc para configurar a instância MockMvc. A classe contém três métodos de teste:
testGetStudents(): Testa o métodogetStudents()da classeStudentControllersimulando o comportamento da interfaceIStudentDAOe executando uma requisição GET para o endpoint/api/v2/students.testGetStudent(): Testa o métodogetStudent()da classeStudentControllersimulando o comportamento da interfaceIStudentDAOe executando uma requisição GET para o endpoint/api/v2/student/20191001.testModifyStudent(): Testa o métodomodifyStudent()da classeStudentControllersimulando o comportamento da interfaceIStudentDAO, convertendo um objeto de estudante de exemplo para JSON e executando uma requisição PUT para o endpoint/api/v2/student.
Executar os Testes
Agora que você criou os arquivos ServiceTests.java e ControllerTests.java, você pode executar os testes para verificar a funcionalidade das classes StudentServiceImpl e StudentController.
- Abra um terminal ou prompt de comando e navegue até o diretório do seu projeto usando o seguinte comando:
cd ~/project/springboottesting/
- Execute o seguinte comando para executar a classe
ServiceTests:
mvn test -Dtest=ServiceTests
Isso executará os três métodos de teste na classe ServiceTests e exibirá os resultados.
- Execute o seguinte comando para executar a classe
ControllerTests:
mvn test -Dtest=ControllerTests
Isso executará os três métodos de teste na classe ControllerTests e exibirá os resultados.
Você deverá ver os resultados dos testes, incluindo quaisquer testes aprovados ou falhados, na saída do console.
Resumo
Parabéns! Você concluiu este projeto. Você pode praticar mais laboratórios no LabEx para aprimorar suas habilidades.



