samedi 7 mars 2020

Testing Spring controllers by (pseudo) directly calling that handler method - acceptable? how to implement it?

In one sentence: I want the MockMvc perform as if I am directly calling the controller.


Details:

Say we have a Restful controller:

class BookController {
    public Book updateBook(int id, Book newBook) {...}
}

A typical Spring integration testing for a RESTful service looks like:

mockMvc.perform(put("/books/1")
                .content("{\"id\":1, \"name\": \"ABC\", ...}")
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON))
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.id", is(1)))
                .andExpect(jsonPath("$.name", is("ABC")))
                ...and more...;

However, can we do things like:

Book result = magicMvc.perform(BookController::updateBook(1, new Book("ABC", ...)));
assertThat(1, result.getId());
assertThat("ABC", result.getName());
...

In one sentence: I want the MockMvc perform as if I am directly calling the controller. My question:

  1. Shall I do it? (Or this is a very bad practice?)
  2. How to do it? I am thinking to hack the part in Spring framework about "finding and parsing controllers", but do not have concrete ideas about how to do that...

P.S. I use Swagger to generate the client-side API adapters. Thus, in clients, I never do things like fetch('/books/1'), but I always do generatedBookControllerApi.updateBook(1, {name: "ABC", ...}). So testing the URL names seems no need.

Thanks very much for any ideas!

Aucun commentaire:

Enregistrer un commentaire