|
| 1 | +package com.gokhana.demo |
| 2 | + |
| 3 | +import com.fasterxml.jackson.databind.ObjectMapper |
| 4 | +import com.gokhana.demo.model.UserDTO |
| 5 | +import com.gokhana.demo.service.UserService |
| 6 | +import org.junit.jupiter.api.Test |
| 7 | +import org.mockito.Mockito |
| 8 | +import org.mockito.internal.matchers.Any |
| 9 | +import org.springframework.beans.factory.annotation.Autowired |
| 10 | +import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest |
| 11 | +import org.springframework.boot.test.mock.mockito.MockBean |
| 12 | +import org.springframework.http.MediaType |
| 13 | +import org.springframework.test.web.servlet.MockMvc |
| 14 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get |
| 15 | +import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post |
| 16 | +import org.springframework.test.web.servlet.result.MockMvcResultMatchers.* |
| 17 | + |
| 18 | +@WebMvcTest |
| 19 | +class UserControllerTests(@Autowired val mockMvc: MockMvc) { |
| 20 | + |
| 21 | + private val mapper = ObjectMapper() |
| 22 | + |
| 23 | + @MockBean |
| 24 | + lateinit var userService: UserService |
| 25 | + |
| 26 | + @Test |
| 27 | + fun `When create user then user created with expected id`() { |
| 28 | + val userDTO = UserDTO(1, "Gökhan", "G-khan") |
| 29 | + Mockito.`when`(userService.createUser(userDTO)).thenReturn(userDTO) |
| 30 | + mockMvc.perform( |
| 31 | + post("/users").contentType(MediaType.APPLICATION_JSON_VALUE).content(mapper.writeValueAsString(userDTO)) |
| 32 | + .accept(MediaType.APPLICATION_JSON) |
| 33 | + ) |
| 34 | + .andExpect(status().isCreated) |
| 35 | + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) |
| 36 | + .andExpect(jsonPath("id").value(userDTO.id)) |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + fun `when retrieve user while user is exists then user returns with expected id`() { |
| 41 | + val userDTO = UserDTO(1, "Gökhan", "G-khan") |
| 42 | + Mockito.`when`(userService.retrieveUser(userDTO.username)).thenReturn(userDTO) |
| 43 | + mockMvc.perform( |
| 44 | + get("/users").param("user", "G-khan").contentType(MediaType.APPLICATION_JSON_VALUE) |
| 45 | + .accept(MediaType.APPLICATION_JSON) |
| 46 | + ) |
| 47 | + .andExpect(status().isOk) |
| 48 | + .andExpect(content().contentType(MediaType.APPLICATION_JSON)) |
| 49 | + .andExpect(jsonPath("id").value(userDTO.id)) |
| 50 | + } |
| 51 | + |
| 52 | + |
| 53 | + @Test |
| 54 | + fun `When retrieve user while user does not exists then user not found`() { |
| 55 | + Mockito.`when`(userService.retrieveUser(Any.ANY.toString())).thenReturn(null) |
| 56 | + mockMvc.perform(get("/users").param("user", "G").contentType(MediaType.APPLICATION_JSON_VALUE) |
| 57 | + .accept(MediaType.APPLICATION_JSON)) |
| 58 | + .andExpect(status().isNotFound) |
| 59 | + } |
| 60 | + |
| 61 | +} |
0 commit comments