Unit Tests in Spring Boot



Controller Tests

import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@WebMvcTest
public class ControllerTests {

@Autowired
private MockMvc mockMvc;

@MockBean
private EmployeeService employeeService;

@Autowired
private ObjectMapper objectMapper;

@Test
public void testSaveEmployee() throws Exception {
Employee employee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

when(employeeService.saveEmployee(any(Employee.class))).thenReturn(employee);


mockMvc.perform(post("/api/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee)))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstName",
is(employee.getFirstName())))
.andExpect(jsonPath("$.lastName",
is(employee.getLastName())))
.andExpect(jsonPath("$.email",
is(employee.getEmail())));

}

@Test
public void testGetAllEmployee() throws Exception {
List<Employee> listOfEmployees = new ArrayList<>();
listOfEmployees.add(Employee.builder().firstName("Ramesh")
                        .lastName("Fadatare").email("ramesh@gmail.com").build());
listOfEmployees.add(Employee.builder().firstName("Tony")
                        .lastName("Stark").email("tony@gmail.com").build());
when(employeeService.getAllEmployees()).thenReturn(listOfEmployees);

mockMvc.perform(get("/api/employees")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.size()", is(listOfEmployees.size())));

}

@Test
public void testGetEmployeeById() throws Exception {
Employee employee = Employee.builder()
.id(1L)
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

when(employeeService.getEmployeeById(employee.getId()))
                            .thenReturn(Optional.of(employee));

mockMvc.perform(get("/api/employees/{id}", employee.getId())
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstName", is(employee.getFirstName())))
.andExpect(jsonPath("$.lastName", is(employee.getLastName())))
.andExpect(jsonPath("$.email", is(employee.getEmail())));

}

@Test
public void testGetEmployeeById_throwException() throws Exception {
Employee employee = Employee.builder()
.id(1L)
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

when(employeeService.getEmployeeById(employee.getId()))
                            .thenReturn(Optional.empty());

mockMvc.perform(get("/api/employees/{id}", employee.getId())
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isNotFound());

}

@Test
public void testUpdateEmployee() throws Exception {
long employeeId = 1L;
Employee savedEmployee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

Employee updatedEmployee = Employee.builder()
.firstName("Ram")
.lastName("Jadhav")
.email("ram@gmail.com")
.build();
when(employeeService.getEmployeeById(employeeId))
.thenReturn(Optional.of(savedEmployee));
when(employeeService.updateEmployee(any(Employee.class)))
.thenReturn(updatedEmployee);

// when - action or the behaviour that we are going test
ResultActions response = mockMvc
                .perform(put("/api/employees/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedEmployee)));


// then - verify the output
response.andExpect(status().isOk())
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstName",
                                    CoreMatchers.is(updatedEmployee.getFirstName())))
.andExpect(jsonPath("$.lastName",
                                    CoreMatchers.is(updatedEmployee.getLastName())))
.andExpect(jsonPath("$.email",
                                    CoreMatchers.is(updatedEmployee.getEmail())));

}

@Test
public void testUpdateEmployee_throwException() throws Exception {
long employeeId = 1L;

Employee updatedEmployee = Employee.builder()
.firstName("Ram")
.lastName("Jadhav")
.email("ram@gmail.com")
.build();
when(employeeService.getEmployeeById(employeeId)).thenReturn(Optional.empty());
//when(employeeService.updateEmployee(any(Employee.class))).thenReturn(updatedEmployee);

// when - action or the behaviour that we are going test
ResultActions response = mockMvc.perform(put("/api/employees/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedEmployee)));


// then - verify the output
response.andExpect(status().isNotFound())
.andDo(print())
.andExpect(status().isNotFound());;

}

@Test
public void testDeleteEmployee() throws Exception {
long employeeId = 1L;

mockMvc.perform(delete("/api/employees/{id}", employeeId))
.andExpect(status().isOk())
.andDo(print());
}


}

Integration Tests

import com.fasterxml.jackson.databind.ObjectMapper;
import net.javaguides.springboot.model.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import net.javaguides.springboot.service.EmployeeService;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
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.test.web.servlet.ResultActions;

import java.util.ArrayList;
import java.util.List;

import static org.hamcrest.Matchers.is;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTestsIT {

@Autowired
private MockMvc mockMvc;

@Autowired
private EmployeeRepository employeeRepository;

@Autowired
private ObjectMapper objectMapper;

@BeforeEach
void setup(){
employeeRepository.deleteAll();
}

@Test
public void testSaveEmployee() throws Exception {
Employee employee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();


mockMvc.perform(post("/api/employees")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(employee)))
.andDo(print())
.andExpect(status().isCreated())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstName",
is(employee.getFirstName())))
.andExpect(jsonPath("$.lastName",
is(employee.getLastName())))
.andExpect(jsonPath("$.email",
is(employee.getEmail())));

}

@Test
public void testGetAllEmployee() throws Exception {
List<Employee> listOfEmployees = new ArrayList<>();
listOfEmployees.add(Employee.builder().firstName("Ramesh")
                            .lastName("Fadatare").email("ramesh@gmail.com").build());
listOfEmployees.add(Employee.builder().firstName("Tony")
                            .lastName("Stark").email("tony@gmail.com").build());

employeeRepository.saveAll(listOfEmployees);

mockMvc.perform(get("/api/employees")
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.size()", is(listOfEmployees.size())));

}

@Test
public void testGetEmployeeById() throws Exception {
Employee employee = Employee.builder()
.id(1L)
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

employeeRepository.save(employee);

mockMvc.perform(get("/api/employees/{id}", employee.getId())
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstName", is(employee.getFirstName())))
.andExpect(jsonPath("$.lastName", is(employee.getLastName())))
.andExpect(jsonPath("$.email", is(employee.getEmail())));

}

@Test
public void testGetEmployeeById_throwException() throws Exception {
Employee employee = Employee.builder()
.id(1L)
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

mockMvc.perform(get("/api/employees/{id}", employee.getId())
.contentType(MediaType.APPLICATION_JSON))
.andDo(print())
.andExpect(status().isNotFound());

}

@Test
public void testUpdateEmployee() throws Exception {
long employeeId = 1L;
Employee savedEmployee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

Employee updatedEmployee = Employee.builder()
.firstName("Ram")
.lastName("Jadhav")
.email("ram@gmail.com")
.build();

employeeRepository.save(savedEmployee);

// when - action or the behaviour that we are going test
ResultActions response = mockMvc.perform(put("/api/employees/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedEmployee)));


// then - verify the output
response.andExpect(status().isOk())
.andDo(print())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.firstName",
                                    CoreMatchers.is(updatedEmployee.getFirstName())))
.andExpect(jsonPath("$.lastName",
                                    CoreMatchers.is(updatedEmployee.getLastName())))
.andExpect(jsonPath("$.email",
                                    CoreMatchers.is(updatedEmployee.getEmail())));

}

@Test
public void testUpdateEmployee_throwException() throws Exception {
long employeeId = 1L;

Employee updatedEmployee = Employee.builder()
.firstName("Ram")
.lastName("Jadhav")
.email("ram@gmail.com")
.build();


// when - action or the behaviour that we are going test
ResultActions response = mockMvc.perform(put("/api/employees/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(updatedEmployee)));


// then - verify the output
response.andExpect(status().isNotFound())
.andDo(print())
.andExpect(status().isNotFound());;

}

@Test
public void testDeleteEmployee() throws Exception {

Employee savedEmployee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

employeeRepository.save(savedEmployee);

mockMvc.perform(delete("/api/employees/{id}", savedEmployee.getId()))
.andExpect(status().isOk())
.andDo(print());
}


}

Repository Tests

import net.javaguides.springboot.model.Employee;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.util.List;
import java.util.Optional;

import static org.junit.Assert.*;
import static org.assertj.core.api.Assertions.*;

@DataJpaTest
/**
* Integration
* @AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
*/

public class RepositoryTests {

@Autowired
private EmployeeRepository employeeRepository;

private Employee employee;

@BeforeEach
public void setUp() {
employee = Employee.builder()
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();
}

@Test
public void saveEmployee() {
Employee savedEmployee = employeeRepository.save(employee);
assertNotNull(savedEmployee);
assertTrue(savedEmployee.getId() > 0);
}

@Test
public void testFindAll() {
Employee employee1 = Employee.builder()
.firstName("David")
.lastName("Beckham")
.email("david@gmail.com")
.build();

employeeRepository.save(employee);
employeeRepository.save(employee1);

List<Employee> employeeList = employeeRepository.findAll();

assertTrue(employeeList.size() == 2);
assertTrue(employeeList.get(0).getFirstName().equals("Ramesh"));
assertEquals(employeeList.get(0).getLastName(), "Fadatare");
assertNotNull(employeeList.get(1));
}

@DisplayName("Test find by Id")
@Test
public void testFindById() {
employeeRepository.save(employee);

Employee foundEmployee = employeeRepository.findById(employee.getId()).get();

assertNotNull(foundEmployee);
}

@Test
public void testDeleteById() {
employeeRepository.save(employee);

employeeRepository.deleteById(employee.getId());
Optional<Employee> employeeOptional = employeeRepository
                                               .findById(employee.getId());

assertThat(employeeOptional).isEmpty();
}

}

Service Tests

import net.javaguides.springboot.exception.ResourceNotFoundException;
import net.javaguides.springboot.model.Employee;
import net.javaguides.springboot.repository.EmployeeRepository;
import net.javaguides.springboot.service.impl.EmployeeServiceImpl;

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

import javax.swing.text.html.Option;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
public class ServiceTests {

@Mock
private EmployeeRepository employeeRepository;

@InjectMocks
private EmployeeServiceImpl employeeService;

private Employee employee;

@BeforeEach
public void setUp() {
employee = Employee.builder()
.id(1L)
.firstName("Ramesh")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();
}

@Test
public void testSaveEmployee() {
when(employeeRepository.findByEmail(employee.getEmail()))
                                .thenReturn(Optional.empty());
when(employeeRepository.save(employee)).thenReturn(employee);
Employee savedEmployee = employeeService.saveEmployee(employee);

assertNotNull(savedEmployee);
assertEquals(savedEmployee.getFirstName(), "Ramesh");
assertEquals(savedEmployee, employee);
assertEquals(savedEmployee, employee);

}

@Test
public void testSaveEmployee_thenThrowsException() {
when(employeeRepository.findByEmail(employee.getEmail()))
                                .thenReturn(Optional.of(employee));

Employee employee1 = Employee.builder()
.firstName("David")
.lastName("Fadatare")
.email("ramesh@gmail.com")
.build();

ResourceNotFoundException exception =
            assertThrows(ResourceNotFoundException.class, () -> {
    employeeService.saveEmployee(employee1);
});

String expectedMessage = "Employee already exists with given email:" +
                                    employee1.getEmail();
String actualMessage = exception.getMessage();
System.out.println(expectedMessage);
System.out.println(actualMessage);
assert actualMessage.contains(expectedMessage);
assertTrue(actualMessage.contains(expectedMessage));
assertTrue(actualMessage.equals(expectedMessage));

}

@Test
public void testGetAllEmployees() {
Employee employee1 = Employee.builder()
.id(2L)
.firstName("Tony")
.lastName("Stark")
.email("tony@gmail.com")
.build();

when(employeeRepository.findAll()).thenReturn(List.of(employee,employee1));

List<Employee> employeeList = employeeService.getAllEmployees();

assertEquals(employeeList.size(), 2);
assertNotNull(employeeList);
}

@Test
public void testGetAllEmployees_returnEmptyList() {
when(employeeRepository.findAll()).thenReturn(Collections.emptyList());

List<Employee> employeeList = employeeService.getAllEmployees();

assertThat(employeeList).isEmpty();
assertEquals(employeeList.size(), 0);

}

@Test
public void testGetEmployeeById() {
when(employeeRepository.findById(employee.getId()))
                        .thenReturn(Optional.of(employee));

Employee employee1 = employeeService.getEmployeeById(employee.getId()).get();

assertEquals(employee1, employee);
}

@Test
public void testUpdateEmployee() {
when(employeeRepository.save(employee)).thenReturn(employee);

employee.setFirstName("David");

Employee updatedEmployee = employeeService.updateEmployee(employee);

verify(employeeRepository, times(1)).save(employee);

assertEquals(updatedEmployee.getFirstName(), "David");
assertEquals(updatedEmployee, employee);
}

@Test
public void testDeleteEmployee() {
long employeeId = 1L;

employeeService.deleteEmployee(employeeId);

verify(employeeRepository, times(1)).deleteById(employeeId);
}

}

DONE

Comments