Spring Unit testing rest controller

人走茶凉 提交于 2019-12-13 03:35:39

问题


What is the best and easiest solution to test these sample get mappings? Could you show some easy example?

@GetMapping("/")
public List<UserDto> get() {
    return userService.getUsers().stream().map((User user) -> toUserDto(user)).collect(Collectors.toList());
}

@GetMapping(path = "/{id}")
public HttpEntity<UserDto> findById(@PathVariable(name = "id") long id) {
    User user = userService.unique(id);
    if (user != null) {
        return new ResponseEntity<>(toUserDto(user), HttpStatus.OK);
    } else {
        return new ResponseEntity<>(HttpStatus.NOT_FOUND);
    }
}

回答1:


Use MockMvc to test controller end points.

@RunWith(MockitoJUnitRunner.class)
public class UserControllerTest {

  @InjectMock
  private UserContoller controller;

  private MockMvc mockMvc;

  @Before
  public void setup() {
    mockMvc = MockMvcBuilders.standaloneSetup(this.controller).build();
  }

  @Test
  public void testFindById() {

     // build your expected results here 
     String url = "/1";
     MvcResult mvcResult = mockMvc
    .perform(MockMvcRequestBuilders.get(url)
    .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();

    String responseAsJson = "some expected response"; 

    Assert.assertEquals("response does not match", mvcResult.getResponse().getContentAsString(),
    responseAsJson);

   // verify the calls
  }
}

EDIT : Adding link to my similar answer here for your reference Spring 5 with JUnit 5 + Mockito - Controller method returns null



来源:https://stackoverflow.com/questions/48891377/spring-unit-testing-rest-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!