I have an authentication controller with the following endpoint
@PostMapping("/register")
fun register(@RequestBody body: RegisterDto): ResponseEntity<User> {
val user = User()
user.name = body.name
user.email = body.email
user.password = body.password
return ResponseEntity.status(201).body(userService.saveUser(user))
}
Now I have written a test case for the above snippet as shown bellow
fun `register user with valid input, returns ok`() {
val result = mockMvc.perform(MockMvcRequestBuilders.post("/api/auth/register")
.param("id","1")
.param("name","Homer")
.param("email","[email protected]")
.param("password","123456")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
result.andExpect(MockMvcResultMatchers.status().isOk)
}
On running, I get 400, and I need to get 200 (successful). I'm quite new to testing on spring boots. What could I be doing wrong or missing? Thanks in andvance
You are setting the params. Actually, You need to pass a JSON body as below:
fun `register user with valid input, returns ok` () {
val user = User()
user.id = 1
user.name = "Homer"
user.email = "[email protected]"
user.password = "123456"
var response = new ObjectMapper().writeValueAsString(user)
val result = mockMvc.perform(MockMvcRequestBuilders.post("/api/auth/register")
.contentType(MediaType.APPLICATION_JSON)
.content(response)
.accept(MediaType.APPLICATION_JSON))
result.andExpect(MockMvcResultMatchers.status().isCreated)
}