Skip to content

Spring Webflux Unit Testing

Ramesh Fadatare edited this page Jan 12, 2023 · 1 revision
package net.javaguides.springbootwebfluxdemo;

import net.javaguides.springbootwebfluxdemo.controller.EmployeeController;
import net.javaguides.springbootwebfluxdemo.dto.EmployeeDto;
import net.javaguides.springbootwebfluxdemo.service.EmployeeService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

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

import static org.mockito.ArgumentMatchers.*;
import static org.mockito.BDDMockito.*;

@ExtendWith(SpringExtension.class)
@WebFluxTest(controllers = EmployeeController.class)
public class EmployeeControllerUnitTests {

    @Autowired
    private WebTestClient webTestClient;

    @MockBean
    private EmployeeService employeeService;

    @Test
    public void givenEmployeeObject_whenCreateEmployee_thenReturnSavedEmployee() throws Exception {

        // given - precondition or setup
        EmployeeDto employee = EmployeeDto.builder()
                .firstName("Ramesh")
                .lastName("Fadatare")
                .email("[email protected]")
                .build();

        given(employeeService.saveEmployee(any(EmployeeDto.class)))
                .willReturn(Mono.just(employee));

        // when - action or behaviour that we are going test
        WebTestClient.ResponseSpec response = webTestClient.post().uri("/api/employees")
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(Mono.just(employee), EmployeeDto.class)
                .exchange();

        // then - verify the result or output using assert statements
        response.expectStatus().isCreated()
                .expectBody()
                .consumeWith(System.out::println)
                .jsonPath("$.firstName").isEqualTo(employee.getFirstName())
                .jsonPath("$.lastName").isEqualTo(employee.getLastName())
                .jsonPath("$.email").isEqualTo(employee.getEmail());
    }

    @Test
    public void givenEmployeeId_whenGetEmployee_thenReturnEmployeeObject() {

        // given - precondition or setup
        String employeeId = "123";
        EmployeeDto employee = EmployeeDto.builder()
                .firstName("John")
                .lastName("Cena")
                .email("[email protected]")
                .build();

        given(employeeService.getEmployee(employeeId)).willReturn(Mono.just(employee));

        // when - action or behaviour that we are going test
        WebTestClient.ResponseSpec response = webTestClient.get()
                .uri("/api/employees/{id}", Collections.singletonMap("id", employeeId))
                .exchange();

        // then - verify the result or output using assert statements
        response.expectStatus().isOk()
                .expectBody()
                .consumeWith(System.out::println)
                .jsonPath("$.firstName").isEqualTo(employee.getFirstName())
                .jsonPath("$.lastName").isEqualTo(employee.getLastName())
                .jsonPath("$.email").isEqualTo(employee.getEmail());
    }

    @Test
    public void givenListOfEmployees_whenGetAllEmployees_thenReturnEmployeesList() {

        // given - precondition or setup
        List<EmployeeDto> listOfEmployees = new ArrayList<>();
        listOfEmployees.add(EmployeeDto.builder().firstName("Ramesh").lastName("Fadatare").email("[email protected]").build());
        listOfEmployees.add(EmployeeDto.builder().firstName("Tony").lastName("Stark").email("[email protected]").build());
        Flux<EmployeeDto> employeeFlux = Flux.fromIterable(listOfEmployees);
        given(employeeService.getAllEmployees()).willReturn(employeeFlux);

        // when - action or behaviour that we are going test
        WebTestClient.ResponseSpec response = webTestClient.get().uri("/api/employees")
                .accept(MediaType.APPLICATION_JSON)
                .exchange();

        // then - verify the result or output using assert statements
        response.expectStatus().isOk()
                .expectHeader().contentType(MediaType.APPLICATION_JSON)
                .expectBodyList(EmployeeDto.class)
                .consumeWith(System.out::println);
    }

    @Test
    public void givenUpdatedEmployee_whenUpdateEmployee_thenReturnUpdatedEmployeeObject() throws Exception {

        // given - precondition or setup
        String employeeId = "123";
        EmployeeDto employee = EmployeeDto.builder()
                .firstName("Ramesh")
                .lastName("Fadatare")
                .email("[email protected]")
                .build();

        EmployeeDto updatedEmployee = EmployeeDto.builder()
                .firstName("ram")
                .lastName("jadhav")
                .email("[email protected]")
                .build();

        // when - action or behaviour that we are going test
        given(employeeService.updateEmployee(any(EmployeeDto.class), any(String.class)))
                .willReturn(Mono.just(employee));

        // when - action or behaviour that we are going test
        WebTestClient.ResponseSpec response = webTestClient.put()
                .uri("api/employees/{id}", Collections.singletonMap("id", employeeId))
                .contentType(MediaType.APPLICATION_JSON)
                .accept(MediaType.APPLICATION_JSON)
                .body(Mono.just(updatedEmployee), EmployeeDto.class)
                .exchange();

        // then - verify the result or output using assert statements
        response.expectStatus().isOk()
                .expectHeader().contentType(MediaType.APPLICATION_JSON)
                .expectBody()
                .consumeWith(System.out::println)
                .jsonPath("$.firstName").isEqualTo(updatedEmployee.getFirstName())
                .jsonPath("$.lastName").isEqualTo(updatedEmployee.getLastName());
    }

    @Test
    public void givenEmployeeId_whenDeleteEmployee_thenReturnNothing() {

        // given - precondition or setup
        String employeeId = "123";
        Mono<Void> voidReturn  = Mono.empty();
        given(employeeService.deleteEmployee(employeeId)).willReturn(voidReturn);

        // when - action or behaviour that we are going test
        WebTestClient.ResponseSpec response = webTestClient.delete()
                .uri("/api/employees/{id}", Collections.singletonMap("id",  employeeId))
                .exchange();

        // then - verify the result or output using assert statements
        response.expectStatus().isNoContent()
                .expectBody()
                .consumeWith(System.out::println);
    }
}
Clone this wiki locally