Unit testing

Let's quickly write a unit test to test the preceding controller method:

    @RunWith(SpringRunner::class)    @WebMvcTest(BasicController::class)    class BasicControllerTest {      @Autowired      lateinit var mvc: MockMvc;      @Test      fun `GET welcome returns "Hello World"`() {        mvc.perform(           MockMvcRequestBuilders.get("/welcome").accept(           MediaType.APPLICATION_JSON))           .andExpect(status().isOk())           .andExpect(content().string(equalTo("Hello World")));       }      }

In the preceding unit test, we will launch up a Mock MVC instance with BasicController. A few quick things to note are as follows:

  • The annotations @RunWith(SpringRunner.class) and @WebMvcTest(BasicController::class) are similar to Java, except for the class references.
  • @Autowired lateinit var mvc: MockMvc ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.