Spring 单元测试休息控制器

Spring Unit testing rest controller

测试这些示例获取映射的最佳和最简单的解决方案是什么?你能举一些简单的例子吗?

@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);
    }
}

使用 MockMvc 测试控制器端点。

@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
  }
}

编辑:将 link 添加到我的类似答案中以供参考 Spring 5 with JUnit 5 + Mockito - Controller method returns null