0

I am getting a result from my unit test that I don't quite understand.

Controller Code

package com.rk.capstone.controllers;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.rk.capstone.model.domain.User;
import com.rk.capstone.model.services.user.IUserService;

/**
 * REST Controller for /register endpoint
 */
@RestController
@RequestMapping("/register")
public class RegisterController {

    private final IUserService userService;

    public RegisterController(IUserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/user", method = RequestMethod.POST)
    public ResponseEntity<User> registerNewUser(@RequestBody User user) {
        if (userService.findByUserName(user.getUserName()) == null) {
            user = userService.saveUser(user);
            return ResponseEntity.status(HttpStatus.CREATED).body(user);
        } else {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(null);
        }
    }
}

Unit Test Code:

package com.rk.capstone.controllers;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rk.capstone.model.dao.UserDao;
import com.rk.capstone.model.domain.User;
import com.rk.capstone.model.services.user.IUserService;

import static org.mockito.BDDMockito.given;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Class Provides Unit Testing for RegisterController
 */
@RunWith(SpringRunner.class)
@WebMvcTest(RegisterController.class)
public class RegisterControllerTest {

    @MockBean
    private IUserService userService;

    @Autowired
    private MockMvc mockMvc;

    private User user;
    private String userJson;

    @Before
    public void setup() {
        user = new User("rick", "k", "rick@email.com", "rkow", "abc123");
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            userJson = objectMapper.writeValueAsString(user);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testRegisterNewUserPostResponse() throws Exception {
        given(this.userService.findByUserName(user.getUserName())).willReturn(null);
        given(this.userService.saveUser(user)).willReturn(user);
        Assert.assertNotNull("Mocked UserService is Null", this.userService);

        this.mockMvc.perform(post("/register/user").content(userJson).
                contentType(MediaType.APPLICATION_JSON)).
                andExpect(status().isCreated()).
                andDo(print()).andReturn();
    }

}

The result of the print() is below, I do not understand why the Body is empty. I have tried numerous things I've read on other posts and blogs and no matter what I try the Body is always empty. Adding a Content-Type header in the controller response makes no difference.

MockHttpServletResponse:
           Status = 201
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

What is confounding me even more, is when I run the actual application and perform a POST using PostMan to the /register/user endpoint the response contains the body and status code I expect, a User represented via JSON, e.g.

Status Code: 201 Created Response Body

{
  "userId": 1,
  "firstName": "rick",
  "lastName": "k",
  "emailAddress": "rick@email.com",
  "userName": "rk",
  "password": "abc123"
}

Any help or ideas is appreciated, using SpringBoot 1.4.0.RELEASE.

UPDATE: For some reason the following mocked method call is returning null in the controller under test.

given(this.userService.saveUser(user)).willReturn(user);

boulderprog
  • 115
  • 1
  • 2
  • 8

1 Answers1

4

This thread ultimately turned me on to a solution:

Mockito when/then not returning expected value

Changed this line:

given(this.userService.saveUser(user)).willReturn(user);

to

given(this.userService.saveUser(any(User.class))).willReturn(user);

Community
  • 1
  • 1
boulderprog
  • 115
  • 1
  • 2
  • 8