I have a simple RestController with a Service and want to test just the controller by providing a mock implementation for the Service.
However, I'm getting an empty response in resultActions = mockMvc.perform(get("/user"));
object when I'm running the test.
Here is my code:
Controller
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/user")
public ResponseEntity<List<String>> getUsers(){
return ResponseEntity.ok().body(userService.getUsers());
}
}
Contoller Test
@RunWith(SpringRunner.class)
@WebMvcTest(UserController.class)
public class UserControllerTest {
@MockBean
UserService userService;
private final Logger log = LoggerFactory.getLogger(UserControllerTest.class);
@Autowired
MockMvc mockMvc;
@Before
public void init(){
List<String> usrs = new ArrayList<>();
usrs.add("JUNIT-USER");
userService = Mockito.mock(UserService.class);
when(userService.getUsers()).thenReturn(usrs);
}
@Test
public void test1() throws Exception {
ResultActions resultActions = mockMvc.perform(get("/user"));
resultActions.andDo(mvcResult -> {
log.info(mvcResult.getResponse().getContentType());
log.info(mvcResult.getResponse().getContentAsString());
log.info(String.valueOf(mvcResult.getResponse().getContentLength()));
});
resultActions
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.content().json("[\"JUNIT-USER\"]"));
}
}
The output of the log statements in the test is as follows:
2021-02-24 15:23:16.161 INFO 22197 --- [ main] com.vi.learn.UserControllerTest : application/json
2021-02-24 15:23:16.161 INFO 22197 --- [ main] com.vi.learn.UserControllerTest : []
2021-02-24 15:23:16.161 INFO 22197 --- [ main] com.vi.learn.UserControllerTest : 0
The test hence fails with the below assertionError:
java.lang.AssertionError: []: Expected 2 values but got 0
What am I doing wrong here?