弹簧单元测试架控制器 [英] Spring Unit testing rest controller

查看:96
本文介绍了弹簧单元测试架控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

使用MockMvc测试控制器端点.

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

这篇关于弹簧单元测试架控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆