mardi 24 septembre 2019

testing Spring Webflux POST endpoint returns 404 and not 202

I created simple API that does not implement full CRUD yet, but i found my first problem. All works great when i run my API with swagger, but when i run tests for Post methods, it seems it rejects my requests.

Tests:

@RunWith(SpringRunner.class)
@WebFluxTest(controllers = CustomerController.class)
@Import(CustomersService.class)
public class CustomerControllerTest {

    @MockBean(answer = Answers.RETURNS_DEEP_STUBS)
    private CustomersService mockedService;

    @Autowired
    private WebTestClient client;

    ...

    @Test
    public void endpointAddWhenGivenGoodJsonShouldReturn202() {
        //todo: fix test, it works in API.
        int id = -1;
        Customer customer1 = new Customer(id, "john", new Address("Krakow", "Stroma", "30-716"));


        Mockito
                .when(mockedService.addCustomer(customer1))
                .thenReturn(Mono.just(customer1));

        client.post()
                .uri("/api/add/")
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Flux.just(customer1), Customer.class)
                .exchange()
                .expectStatus().isCreated();
    }

    @Test
    public void endpointAddWhenGivenGoodJsonShouldReturn404() {

        int id = -1;
        Customer customer1 = new Customer(id, "john", new Address("Krakow", "Stroma", "30-716"));


        Mockito
                .when(mockedService.addCustomer(customer1))
                .thenReturn(Mono.empty());

        client.post()
                .uri("/api/add/")
                .accept(MediaType.APPLICATION_JSON_UTF8)
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .body(Mono.just(customer1), Customer.class)
                .exchange()
                .expectStatus().isNotFound();
    }


}

both tests seems returning isNotFound().

Service class:

@Service
public class CustomersService implements CustomersServiceInterface {
    private final RepositoryInterface customersRepository;

    public CustomersService(RepositoryInterface customersRepository) {
        this.customersRepository = customersRepository;
    }

    public Flux<Customer> getCustomerById(int id) {
        return customersRepository.getById(id);
    }

    public Flux<Customer> getAllCustomers() {
        return customersRepository.getAll();
    }

    public Mono<Customer> addCustomer(Customer newCustomer) {
        return customersRepository.saveCustomer(newCustomer);
    }
}

that is mocked, so repository does not matter.

How can i fix test endpointAddWhenGivenGoodJsonShouldReturn202 to behave like api does, ergo returning good status code?

Aucun commentaire:

Enregistrer un commentaire