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: This autowires the MockMvc bean that can be used to make requests. Properties declared as non-null must be initialized in the constructor. For properties that are autowired through the dependency injection, we can avoid null checks by adding lateinit to the variable declaration.
- fun `GET welcome returns "Hello World"`(): This is a unique feature of Kotlin. Instead of giving the test method a name, we are giving a description for the test. This is awesome because, ideally, the test method will not be called from another method.
- mvc.perform(MockMvcRequestBuilders.get("/welcome").accept(MediaType.APPLICATION_JSON)): This performs a request to /welcome with the Accept header value, application/json, which is similar to the Java code.
- andExpect(status().isOk()): This expects that the status of the response is 200 (success).
- andExpect(content().string(equalTo("Hello World"))): This expects that the content of the response is equal to "Hello World".