Skip to content
Snippets Groups Projects
Commit 3bebeb22 authored by Burhan Akbar's avatar Burhan Akbar
Browse files

Fix and enhance MockMvc tests for NursingHomeController

parent 27ea4028
Branches 24-hotfix-development-directory
No related tags found
No related merge requests found
......@@ -3,10 +3,12 @@ package com.cardiff.client_project.controller.nursinghome;
import com.cardiff.client_project.pojo.dto.HospitalDTO;
import com.cardiff.client_project.service.NursingHomeService;
import com.cardiff.client_project.utils.Result;
import com.fasterxml.jackson.databind.ObjectMapper; // Needed for POST/PUT JSON conversion
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; // Add this import
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
......@@ -18,14 +20,19 @@ import java.util.List;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.hamcrest.Matchers.*; // For jsonPath checks
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; // Add this import
// Use @WebMvcTest to test only the controller layer, mocking dependencies
@WebMvcTest(NursingHomeController.class)
@AutoConfigureMockMvc(addFilters = false) // <--- ADD THIS LINE TO DISABLE SECURITY FILTERS FOR THE TEST
public class NursingHomeControllerBurTest {
@Autowired
private MockMvc mockMvc; // Allows sending HTTP requests to the controller
@Autowired
private ObjectMapper objectMapper; // Utility to convert objects to JSON for POST/PUT
@MockBean // Creates a Mockito mock for the service layer
private NursingHomeService nursingHomeService;
......@@ -33,7 +40,7 @@ public class NursingHomeControllerBurTest {
@BeforeEach
void setUp() {
// Create a sample DTO for testing POST/PUT if needed
// Create a sample DTO for testing
sampleHospitalDTO = new HospitalDTO();
sampleHospitalDTO.setId(1);
sampleHospitalDTO.setName("Test Hospital");
......@@ -41,7 +48,7 @@ public class NursingHomeControllerBurTest {
sampleHospitalDTO.setPhone("1234567890");
sampleHospitalDTO.setTotalBeds(100);
sampleHospitalDTO.setAvailableBeds(50);
sampleHospitalDTO.setApprovalStatus("APPROVED");
sampleHospitalDTO.setApprovalStatus("APPROVED"); // Assuming default is approved for some tests
}
@Test
......@@ -52,12 +59,16 @@ public class NursingHomeControllerBurTest {
Mockito.when(nursingHomeService.getAvailableBeds()).thenReturn(successResult);
// Act & Assert: Perform the GET request and check the response
mockMvc.perform(get("/api/hospitals/available"))
mockMvc.perform(get("/api/hospitals/available")
.accept(MediaType.APPLICATION_JSON)) // Specify we accept JSON
.andDo(print()) // <--- ADD THIS LINE TO PRINT THE RESPONSE
.andExpect(status().isOk()) // Check for HTTP 200 OK
.andExpect(content().contentType(MediaType.APPLICATION_JSON)) // Check content type
.andExpect(jsonPath("$.code", is(1))) // Check Result success code
.andExpect(jsonPath("$.msg").doesNotExist()) // Success shouldn't have a message
.andExpect(jsonPath("$.data", hasSize(1))) // Check if data array has 1 item
.andExpect(jsonPath("$.data[0].name", is("Test Hospital"))); // Check the name of the hospital
.andExpect(jsonPath("$.data[0].id", is(1)))
.andExpect(jsonPath("$.data[0].name", is("Test Hospital"))); // Check the name
}
@Test
......@@ -67,11 +78,13 @@ public class NursingHomeControllerBurTest {
Mockito.when(nursingHomeService.getAvailableBeds()).thenReturn(errorResult);
// Act & Assert: Perform the GET request and check the error response
mockMvc.perform(get("/api/hospitals/available"))
mockMvc.perform(get("/api/hospitals/available")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk()) // Controller still returns OK, but Result contains error
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", is(0))) // Check Result error code
.andExpect(jsonPath("$.msg", is("Database unavailable"))); // Check error message
.andExpect(jsonPath("$.msg", is("Database unavailable"))) // Check error message
.andExpect(jsonPath("$.data").doesNotExist()); // Error shouldn't have data
}
@Test
......@@ -82,29 +95,32 @@ public class NursingHomeControllerBurTest {
Mockito.when(nursingHomeService.searchHospitals(Mockito.eq("Test"))).thenReturn(successResult);
// Act & Assert
mockMvc.perform(get("/api/hospitals/search").param("name", "Test"))
mockMvc.perform(get("/api/hospitals/search").param("name", "Test")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", is(1)))
.andExpect(jsonPath("$.data", hasSize(1)))
.andExpect(jsonPath("$.data[0].name", is("Test Hospital")));
}
@Test
void testSearchHospitals_WithEmptyName_CallsGetAvailableBeds() throws Exception {
// Arrange
// Arrange: Mock the getAvailableBeds call which should be triggered
List<HospitalDTO> hospitalList = Collections.singletonList(sampleHospitalDTO);
Result<List<HospitalDTO>> successResult = Result.success(hospitalList);
// When search is called with empty/null, it should delegate to getAvailableBeds
Mockito.when(nursingHomeService.getAvailableBeds()).thenReturn(successResult);
// Act & Assert
mockMvc.perform(get("/api/hospitals/search").param("name", ""))
mockMvc.perform(get("/api/hospitals/search").param("name", "") // Empty name
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", is(1)))
.andExpect(jsonPath("$.data", hasSize(1)))
.andExpect(jsonPath("$.data[0].name", is("Test Hospital")));
// Verify that searchHospitals was NOT called, but getAvailableBeds WAS called
// Verify that searchHospitals was NOT called, but getAvailableBeds WAS called exactly once
Mockito.verify(nursingHomeService, Mockito.never()).searchHospitals(Mockito.anyString());
Mockito.verify(nursingHomeService, Mockito.times(1)).getAvailableBeds();
}
......@@ -113,28 +129,78 @@ public class NursingHomeControllerBurTest {
void testDeleteHospital_ReturnsOk() throws Exception {
// Arrange
Result<String> successResult = Result.success("Hospital deleted successfully");
// Ensure the mock matches the controller's call: deletePatientById(List.of(id))
Mockito.when(nursingHomeService.deletePatientById(Mockito.eq(List.of(1)))).thenReturn(successResult);
// Act & Assert
mockMvc.perform(delete("/api/hospitals/{id}", 1))
mockMvc.perform(delete("/api/hospitals/{id}", 1) // Use path variable
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", is(1)))
.andExpect(jsonPath("$.msg", is("Hospital deleted successfully")));
.andExpect(jsonPath("$.msg", is("Hospital deleted successfully")))
.andExpect(jsonPath("$.data").doesNotExist());
}
// --- Add tests for POST and PUT ---
@Test
void testGetAvailableBedsEndpoint() throws Exception {
// Optional: Mock the service call if needed
// We need to mock it for the test to pass consistently, even if just returning success with empty list
Mockito.when(nursingHomeService.getAvailableBeds()).thenReturn(Result.success(List.of()));
void testAddHospital_ReturnsOkAndData() throws Exception {
// Arrange
// Prepare the DTO to be sent in the request body
HospitalDTO requestDTO = new HospitalDTO();
requestDTO.setName("New Hospital");
requestDTO.setLocation("New Location");
requestDTO.setPhone("9876543210");
requestDTO.setTotalBeds(200);
requestDTO.setAvailableBeds(150);
// Note: The service sets the PENDING status, so we don't set it here
// Mock the service response (it should return the DTO with PENDING status)
HospitalDTO responseDTO = new HospitalDTO(); // Simulate what the service returns
responseDTO.setId(2); // Assume DB assigns ID 2
responseDTO.setName("New Hospital");
responseDTO.setLocation("New Location");
responseDTO.setPhone("9876543210");
responseDTO.setTotalBeds(200);
responseDTO.setAvailableBeds(150);
responseDTO.setApprovalStatus("PENDING"); // Service sets this
Result<HospitalDTO> successResult = Result.success(responseDTO);
// Mock the service call - use Mockito.any(HospitalDTO.class) as the exact object might differ
Mockito.when(nursingHomeService.insertPatientInfo(Mockito.any(HospitalDTO.class))).thenReturn(successResult);
mockMvc.perform(get("/api/hospitals/available")) // Test your GET endpoint
.andExpect(status().isOk()); // Check if it returns HTTP 200 OK
// Act & Assert
mockMvc.perform(post("/api/hospitals")
.contentType(MediaType.APPLICATION_JSON) // Set Content-Type for request body
.content(objectMapper.writeValueAsString(requestDTO)) // Convert DTO to JSON string
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", is(1)))
.andExpect(jsonPath("$.data.id", is(2)))
.andExpect(jsonPath("$.data.name", is("New Hospital")))
.andExpect(jsonPath("$.data.approvalStatus", is("PENDING"))); // Verify status
}
// Add more tests for POST, PUT, /pending, /approval etc. following the same pattern:
// 1. Arrange: Mock the service call (Mockito.when(...).thenReturn(...))
// 2. Act: Perform the request using mockMvc.perform(...)
// 3. Assert: Check the status, content type, and JSON payload using .andExpect(...)
@Test
void testUpdateBedCount_ReturnsOk() throws Exception {
// Arrange
int hospitalId = 1;
int currentPatients = 60;
Result<String> successResult = Result.success("Bed count updated successfully");
Mockito.when(nursingHomeService.updateBedCount(hospitalId, currentPatients)).thenReturn(successResult);
// Act & Assert
mockMvc.perform(put("/api/hospitals/{hospitalId}/beds", hospitalId)
.param("currentPatients", String.valueOf(currentPatients)) // Send as request parameter
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.code", is(1)))
.andExpect(jsonPath("$.msg", is("Bed count updated successfully")));
}
// Add tests for /pending and /approval endpoints if needed
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment