Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file modified Spring-Boot-CRUD/Spring-Boot-CRUD/mvnw
100644 → 100755
Empty file.
10 changes: 10 additions & 0 deletions Spring-Boot-CRUD/Spring-Boot-CRUD/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,21 @@
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,4 @@ public ResponseStructure<Student> updateStudent(@RequestBody Student student, @P
public ResponseStructure<String> deleteStudent(@PathVariable int id){
return studentService.deleteStudent(id);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public ResponseStructure<Student> saveStudent(Student student){
responseStructure.setMessage("Student saved successfully");
} else {
responseStructure.setData(null);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
responseStructure.setMessage("Student has failed to save");
}
return responseStructure;
Expand All @@ -38,12 +38,12 @@ public ResponseStructure<Student> getStudentById(Integer id){
Student student = studentDao.getStudentById(id);
if(student != null) {
responseStructure.setData(student);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setMessage("Student got by id");
responseStructure.setStatusCode(HttpStatus.OK.value());
responseStructure.setMessage("Student retrieved successfully");
} else {
responseStructure.setData(null);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setMessage("Student don't exists");
responseStructure.setStatusCode(HttpStatus.NOT_FOUND.value());
responseStructure.setMessage("Student not found");
}
return responseStructure;
}
Expand All @@ -52,15 +52,9 @@ public ResponseStructure<Student> getStudentById(Integer id){
public ResponseStructure<List<Student>> getAllStudent(){
ResponseStructure<List<Student>> responseStructure = new ResponseStructure<List<Student>>();
List<Student> student = studentDao.getAllStudent();
if(student.size() > 0) {
responseStructure.setData(student);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setMessage("Here are the list of all Students");
} else {
responseStructure.setData(null);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setMessage("No student record exists in database");
}
responseStructure.setData(student);
responseStructure.setStatusCode(HttpStatus.OK.value());
responseStructure.setMessage("Students retrieved successfully");
return responseStructure;
}

Expand All @@ -70,12 +64,12 @@ public ResponseStructure<Student> updateStudent(Student student, Integer id){
Student student1 = studentDao.updateStudent(student, id);
if(student1 != null) {
responseStructure.setData(student1);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setStatusCode(HttpStatus.OK.value());
responseStructure.setMessage("Student updated successfully");
} else {
responseStructure.setData(null);
responseStructure.setStatusCode(HttpStatus.CREATED.value());
responseStructure.setMessage("Student don't exists");
responseStructure.setStatusCode(HttpStatus.NOT_FOUND.value());
responseStructure.setMessage("Student not found for update");
}
return responseStructure;
}
Expand All @@ -85,14 +79,14 @@ public ResponseStructure<String> deleteStudent(Integer id){
ResponseStructure<String> responseStructure = new ResponseStructure<String>();
boolean isTrue = studentDao.deleteStudent(id);
if(isTrue) {
responseStructure.setData("Student selected");
responseStructure.setData("Student deleted");
responseStructure.setStatusCode(HttpStatus.OK.value());
responseStructure.setMessage("Student deleted successfully");
} else {
responseStructure.setData("Student not selected");
responseStructure.setStatusCode(HttpStatus.OK.value());
responseStructure.setMessage("Student has failed to get delete");
responseStructure.setData(null);
responseStructure.setStatusCode(HttpStatus.NOT_FOUND.value());
responseStructure.setMessage("Student not found for deletion");
}
return responseStructure;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
spring.datasource.url= jdbc:mysql://localhost:3306/spring_boot_crud
spring.datasource.url= jdbc:mysql://localhost:3306/Student
spring.datasource.username=root
spring.datasource.password=root

Expand All @@ -7,5 +7,6 @@ spring.jpa.properties.hibernate.format_sql=true
spring.jpa.show-sql=true

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
spring.jpa.open-in-view=false

spring.mvc.pathmatch.matching-strategy=ant-path-matcher
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
package com.jsp.SpringBootCRUD.Controller;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

import java.util.Arrays;
import java.util.List;

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.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsp.SpringBootCRUD.Dto.ResponseStructure;
import com.jsp.SpringBootCRUD.Dto.Student;
import com.jsp.SpringBootCRUD.Service.StudentService;

@WebMvcTest(StudentController.class)
public class StudentControllerMockMvcTest {

@Autowired
private MockMvc mockMvc;

@MockBean
private StudentService studentService;

@Autowired
private ObjectMapper objectMapper;

private Student student;
private ResponseStructure<Student> successResponse;
private ResponseStructure<String> deleteResponse;

@BeforeEach
void setUp() {
student = new Student();
student.setId(1);
student.setName("John Doe");
student.setEmail("john@example.com");

successResponse = new ResponseStructure<>();
successResponse.setStatusCode(200);
successResponse.setMessage("Student retrieved successfully");
successResponse.setData(student);

deleteResponse = new ResponseStructure<>();
deleteResponse.setStatusCode(200);
deleteResponse.setMessage("Student deleted successfully");
deleteResponse.setData("Student deleted");
}

@Test
void testSaveStudent() throws Exception {
ResponseStructure<Student> saveResponse = new ResponseStructure<>();
saveResponse.setStatusCode(201);
saveResponse.setMessage("Student saved successfully");
saveResponse.setData(student);

when(studentService.saveStudent(any(Student.class))).thenReturn(saveResponse);

mockMvc.perform(post("/student")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(student)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(201))
.andExpect(jsonPath("$.message").value("Student saved successfully"))
.andExpect(jsonPath("$.data.name").value("John Doe"))
.andExpect(jsonPath("$.data.email").value("john@example.com"));
}

@Test
void testGetStudentById() throws Exception {
when(studentService.getStudentById(1)).thenReturn(successResponse);

mockMvc.perform(get("/student/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Student retrieved successfully"))
.andExpect(jsonPath("$.data.id").value(1))
.andExpect(jsonPath("$.data.name").value("John Doe"));
}

@Test
void testGetAllStudents() throws Exception {
List<Student> students = Arrays.asList(student);
ResponseStructure<List<Student>> listResponse = new ResponseStructure<>();
listResponse.setStatusCode(200);
listResponse.setMessage("Students retrieved successfully");
listResponse.setData(students);

when(studentService.getAllStudent()).thenReturn(listResponse);

mockMvc.perform(get("/student"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Students retrieved successfully"))
.andExpect(jsonPath("$.data[0].name").value("John Doe"));
}

@Test
void testUpdateStudent() throws Exception {
ResponseStructure<Student> updateResponse = new ResponseStructure<>();
updateResponse.setStatusCode(200);
updateResponse.setMessage("Student updated successfully");
updateResponse.setData(student);

when(studentService.updateStudent(any(Student.class), eq(1))).thenReturn(updateResponse);

mockMvc.perform(put("/student/1")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(student)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Student updated successfully"))
.andExpect(jsonPath("$.data.name").value("John Doe"));
}

@Test
void testDeleteStudent() throws Exception {
when(studentService.deleteStudent(1)).thenReturn(deleteResponse);

mockMvc.perform(delete("/student/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(200))
.andExpect(jsonPath("$.message").value("Student deleted successfully"))
.andExpect(jsonPath("$.data").value("Student deleted"));
}

@Test
void testGetStudentByIdNotFound() throws Exception {
ResponseStructure<Student> notFoundResponse = new ResponseStructure<>();
notFoundResponse.setStatusCode(404);
notFoundResponse.setMessage("Student not found");

when(studentService.getStudentById(999)).thenReturn(notFoundResponse);

mockMvc.perform(get("/student/999"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(404))
.andExpect(jsonPath("$.message").value("Student not found"));
}

// Negative Test Cases

@Test
void testUpdateStudentNotFound() throws Exception {
ResponseStructure<Student> notFoundResponse = new ResponseStructure<>();
notFoundResponse.setStatusCode(404);
notFoundResponse.setMessage("Student not found for update");

when(studentService.updateStudent(any(Student.class), eq(999))).thenReturn(notFoundResponse);

mockMvc.perform(put("/student/999")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(student)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(404))
.andExpect(jsonPath("$.message").value("Student not found for update"));
}

@Test
void testDeleteStudentNotFound() throws Exception {
ResponseStructure<String> notFoundResponse = new ResponseStructure<>();
notFoundResponse.setStatusCode(404);
notFoundResponse.setMessage("Student not found for deletion");

when(studentService.deleteStudent(999)).thenReturn(notFoundResponse);

mockMvc.perform(delete("/student/999"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(404))
.andExpect(jsonPath("$.message").value("Student not found for deletion"));
}

@Test
void testSaveStudentWithInvalidEmail() throws Exception {
Student invalidStudent = new Student();
invalidStudent.setId(1);
invalidStudent.setName("John Doe");
invalidStudent.setEmail("invalid-email"); // Invalid email format

ResponseStructure<Student> saveResponse = new ResponseStructure<>();
saveResponse.setStatusCode(400);
saveResponse.setMessage("Invalid email format");
saveResponse.setData(invalidStudent);

when(studentService.saveStudent(any(Student.class))).thenReturn(saveResponse);

mockMvc.perform(post("/student")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(invalidStudent)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(400))
.andExpect(jsonPath("$.message").value("Invalid email format"));
}

@Test
void testSaveStudentWithEmptyName() throws Exception {
Student emptyNameStudent = new Student();
emptyNameStudent.setId(1);
emptyNameStudent.setName(""); // Empty name
emptyNameStudent.setEmail("john@example.com");

ResponseStructure<Student> saveResponse = new ResponseStructure<>();
saveResponse.setStatusCode(400);
saveResponse.setMessage("Name is required");
saveResponse.setData(emptyNameStudent);

when(studentService.saveStudent(any(Student.class))).thenReturn(saveResponse);

mockMvc.perform(post("/student")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(emptyNameStudent)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(400))
.andExpect(jsonPath("$.message").value("Name is required"));
}

@Test
void testSaveStudentWithInvalidJson() throws Exception {
String invalidJson = "{invalid json}";

mockMvc.perform(post("/student")
.contentType(MediaType.APPLICATION_JSON)
.content(invalidJson))
.andExpect(status().isBadRequest());
}

@Test
void testSaveStudentWithEmptyBody() throws Exception {
String emptyBody = "{}";

ResponseStructure<Student> saveResponse = new ResponseStructure<>();
saveResponse.setStatusCode(400);
saveResponse.setMessage("Invalid request body");
saveResponse.setData(null);

when(studentService.saveStudent(any(Student.class))).thenReturn(saveResponse);

mockMvc.perform(post("/student")
.contentType(MediaType.APPLICATION_JSON)
.content(emptyBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$.statusCode").value(400))
.andExpect(jsonPath("$.message").value("Invalid request body"));
}

@Test
void testGetStudentByIdWithInvalidPathVariable() throws Exception {
mockMvc.perform(get("/student/abc"))
.andExpect(status().isBadRequest());
}
}
Loading