Commit 385e5207 authored by mrekkala's avatar mrekkala

Added Junit test case for exception scenario's

parent e4d83a56
...@@ -70,6 +70,11 @@ ...@@ -70,6 +70,11 @@
<artifactId>reactor-test</artifactId> <artifactId>reactor-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
...@@ -38,7 +38,7 @@ public class EmployeeController { ...@@ -38,7 +38,7 @@ public class EmployeeController {
@GetMapping @GetMapping
public ResponseEntity<Flux<EmployeeDto>> getEmployee(){ public ResponseEntity<Flux<EmployeeDto>> getEmployee(){
log.info("getEmployee"); log.info("getEmployee details");
return ResponseEntity.ok(employeeService.getAllEmployees()); return ResponseEntity.ok(employeeService.getAllEmployees());
} }
...@@ -66,10 +66,10 @@ public class EmployeeController { ...@@ -66,10 +66,10 @@ public class EmployeeController {
} }
@GetMapping("/kafka/send/{id}") @GetMapping("/kafka/send/{message}")
public ResponseEntity<Mono<EmployeeDto>> sendDataToKafkaTopic(@PathVariable String id){ public String sendDataToKafkaTopic(@PathVariable String message){
kafkaProducerService.sendMessage(id); return kafkaProducerService.sendMessage(message);
return null;
} }
} }
......
package com.nisum.webflux_poc.model;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@Component
public class FileUtil {
public static String readFromFileToString(String filePath) throws IOException {
File resource = new ClassPathResource(filePath).getFile();
byte[] byteArray = Files.readAllBytes(resource.toPath());
return new String(byteArray);
}
}
...@@ -22,10 +22,10 @@ public class KafkaProducerService { ...@@ -22,10 +22,10 @@ public class KafkaProducerService {
this.kafkaTemplate = kafkaTemplate; this.kafkaTemplate = kafkaTemplate;
} }
// Sending message to a topic asynchronously and reactively public String sendMessage(String message) {
public void sendMessage(String message) {
kafkaTemplate.send(topic, message); kafkaTemplate.send(topic, message);
return "message sent successfully";
} }
......
package com.nisum.webflux_poc.utills; package com.nisum.webflux_poc.utills;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nisum.webflux_poc.model.Employee; import com.nisum.webflux_poc.model.Employee;
import com.nisum.webflux_poc.dto.EmployeeDto; import com.nisum.webflux_poc.dto.EmployeeDto;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class AppUtils { public class AppUtils {
...@@ -18,4 +25,20 @@ public class AppUtils { ...@@ -18,4 +25,20 @@ public class AppUtils {
return employee; return employee;
} }
public static List<EmployeeDto> readFile(String filePath) throws IOException {
File file = new ClassPathResource(filePath).getFile();
ObjectMapper objectMapper = new ObjectMapper();
List<EmployeeDto> employeeList = objectMapper.readValue(file, new TypeReference<List<EmployeeDto>>() {});
return employeeList;
}
public static EmployeeDto readEmployeeFile(String filePath) throws IOException {
File file = new ClassPathResource(filePath).getFile();
ObjectMapper objectMapper = new ObjectMapper();
EmployeeDto employee = objectMapper.readValue(file, EmployeeDto.class);
return employee;
}
} }
...@@ -2,8 +2,10 @@ package com.nisum.webflux_poc; ...@@ -2,8 +2,10 @@ package com.nisum.webflux_poc;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
@SpringBootTest @SpringBootTest
@ActiveProfiles(value = "test")
class WebfluxPocApplicationTests { class WebfluxPocApplicationTests {
@Test @Test
......
...@@ -3,27 +3,37 @@ package com.nisum.webflux_poc.controller; ...@@ -3,27 +3,37 @@ package com.nisum.webflux_poc.controller;
import com.nisum.webflux_poc.dto.EmployeeDto; import com.nisum.webflux_poc.dto.EmployeeDto;
import com.nisum.webflux_poc.repository.EmployeeRepository; import com.nisum.webflux_poc.repository.EmployeeRepository;
import com.nisum.webflux_poc.service.EmployeeService; import com.nisum.webflux_poc.service.EmployeeService;
import com.nisum.webflux_poc.service.KafkaProducerService;
import com.nisum.webflux_poc.utills.AppUtils;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito; import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest; import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.reactive.server.WebTestClient; import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import java.io.IOException;
import java.util.List;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class) @ExtendWith(MockitoExtension.class)
@WebFluxTest(EmployeeController.class) @WebFluxTest(EmployeeController.class)
public class EmployeeControllerTest { public class EmployeeControllerTest {
@MockBean @MockBean
EmployeeService employeeService; EmployeeService employeeService;
...@@ -33,29 +43,29 @@ public class EmployeeControllerTest { ...@@ -33,29 +43,29 @@ public class EmployeeControllerTest {
@Autowired @Autowired
private WebTestClient webTestClient; private WebTestClient webTestClient;
private EmployeeDto employee; @MockBean
private EmployeeDto employee1; KafkaProducerService kafkaProducerService;
@BeforeEach @Value("${spring.kafka.template.default-topic}")
void setUp(){ private String topic;
employee=new EmployeeDto(); List<EmployeeDto> employeeList;
employee.setId("1");
employee.setName("manasa");
employee.setSalary(1234);
employee1=new EmployeeDto(); private EmployeeDto employee;
employee1.setId("2");
employee1.setName("asd");
employee1.setSalary(23456); @BeforeEach
ReflectionTestUtils.setField(employeeService, "employeeRepository", employeeRepository); void setUp() throws IOException {
employeeList = AppUtils.readFile("static/request/EmployeeList.json");
employee = AppUtils.readEmployeeFile("static/request/Employee.json");
ReflectionTestUtils.setField(kafkaProducerService,"topic",topic);
} }
@Test @Test
void saveEmployeeDataTest(){ void getEmployeeDataTest() throws IOException {
when(employeeService.getAllEmployees()).thenReturn(Flux.just(employee, employee1)); when(employeeService.getAllEmployees()).thenReturn(Flux.fromIterable(employeeList));
webTestClient.get() webTestClient.get()
.uri("/employee") .uri("/employee")
.exchange() .exchange()
...@@ -64,13 +74,61 @@ public class EmployeeControllerTest { ...@@ -64,13 +74,61 @@ public class EmployeeControllerTest {
.expectBodyList(EmployeeDto.class); .expectBodyList(EmployeeDto.class);
} }
@Test
void testGetEmployee_NoContent() {
when(employeeService.getAllEmployees())
.thenReturn(Flux.empty()); // Simulates failure to save
webTestClient.get()
.uri("/employee")
.exchange()
.expectStatus().isOk()
.expectBodyList(EmployeeDto.class)
.hasSize(0);
}
@Test
void testGetEmployee_InternalServerError() {
when(employeeService.getAllEmployees())
.thenReturn(Flux.error(new RuntimeException("Database error")));
webTestClient.get()
.uri("/employee")
.exchange()
.expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Test
void testSaveEmployee_BadRequest() {
when(employeeService.saveEmployeeData(any(Mono.class)))
.thenReturn(Mono.empty()); // Simulates failure to save
webTestClient.post()
.uri("/employee/save")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(employee)
.exchange()
.expectStatus().isBadRequest();
}
@Test
void testSaveEmployee_InternalServerError() {
when(employeeService.saveEmployeeData(any(Mono.class)))
.thenReturn(Mono.error(new RuntimeException("Database error"))); // Simulate error
webTestClient.post()
.uri("/employee/save")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(employee)
.exchange()
.expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Test @Test
void saveEmployeeTest(){ void saveEmployeeTest(){
/*EmployeeDto employee2=new EmployeeDto();
employee2.setId("1");
employee2.setName("manasa");
employee2.setSalary(1234);*/
when(employeeService.saveEmployeeData(any(Mono.class))).thenReturn(Mono.just(employee)); when(employeeService.saveEmployeeData(any(Mono.class))).thenReturn(Mono.just(employee));
webTestClient.post() webTestClient.post()
...@@ -98,7 +156,31 @@ public class EmployeeControllerTest { ...@@ -98,7 +156,31 @@ public class EmployeeControllerTest {
} }
@Test @Test
void getEmployeeTest(){ void testUpdateEmployee_NotFound(){
String employeeId="1";
Mockito.when(employeeService.getEmployee(any(String.class))).thenReturn(Mono.empty());
webTestClient.put()
.uri("/employee/update/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(employee)
.exchange()
.expectStatus().isOk()
.expectBody(Void.class);
}
@Test
void testUpdateEmployee_BadRequest(){
String employeeId="1";
Mockito.when(employeeService.getEmployee(any(String.class)))
.thenReturn(Mono.error(new RuntimeException("Bad request")));
webTestClient.put()
.uri("/employee/update/{id}", employeeId)
.contentType(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isEqualTo(HttpStatus.BAD_REQUEST);
}
@Test
void getEmployeeWithIdTest(){
String employeeId="1"; String employeeId="1";
Mono<EmployeeDto> employeeDto= Mono.just(employee); Mono<EmployeeDto> employeeDto= Mono.just(employee);
when(employeeService.getEmployee(employeeId)).thenReturn(employeeDto); when(employeeService.getEmployee(employeeId)).thenReturn(employeeDto);
...@@ -110,6 +192,20 @@ public class EmployeeControllerTest { ...@@ -110,6 +192,20 @@ public class EmployeeControllerTest {
.expectBodyList(EmployeeDto.class); .expectBodyList(EmployeeDto.class);
} }
@Test
void testDeleteEmployee_NotFound() {
String employeeId = "123";
when(employeeService.deleteEmployee(employeeId))
.thenReturn(Mono.error(new RuntimeException("Database error"))); // Simulate error
webTestClient.delete()
.uri("/employee/delete/{id}", employeeId)
.exchange()
.expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Test @Test
void deleteEmployeeTest(){ void deleteEmployeeTest(){
String employeeId="1"; String employeeId="1";
...@@ -134,5 +230,40 @@ public class EmployeeControllerTest { ...@@ -134,5 +230,40 @@ public class EmployeeControllerTest {
.expectBodyList(Double.class); .expectBodyList(Double.class);
} }
@Test
void getAverageSalaryTestWithException(){
Double averageSalary= 90.9;
Mockito.when(employeeService.getAverageSalary()).thenReturn(Flux.error(new RuntimeException("internal server error")));
webTestClient.get()
.uri("/employee/average/salary")
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
@Test
void sendDataToKafkaTopicTest(){
String message = "manasa";
Mockito.when(kafkaProducerService.sendMessage(anyString())).thenReturn("test");
webTestClient.get()
.uri("/employee/kafka/send/{message}", message)
.exchange()
.expectStatus()
.is2xxSuccessful();
}
@Test
void sendDataToKafkaTopicWithException(){
String message = "manasa";
Mockito.when(kafkaProducerService.sendMessage(anyString())).thenThrow(new RuntimeException("internal server error"));
webTestClient.get()
.uri("/employee/kafka/send/{message}", message)
.exchange()
.expectStatus()
.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR);
}
} }
spring:
data:
mongodb:
database: Test
host: localhost
port: 27017
kafka:
producer:
bootstrap-servers: localhost:9092,localhost:9093,localhost:9094
key-serializer: org.apache.kafka.common.serialization.StringSerializer
value-serializer: org.apache.kafka.common.serialization.StringSerializer
template:
default-topic: test
server:
port: 9292
[
{
"id": "132",
"name": "manasa",
"salary": 1234.0
},
{
"id": "138",
"name": "abc",
"salary": 1234.0
}
]
\ No newline at end of file
{
"id": "132",
"name": "manasa",
"salary": 1234.0
}
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment