【问题标题】:Spring Unit testing rest controllerSpring单元测试休息控制器
【发布时间】:2018-07-31 04:13:51
【问题描述】:

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

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

【问题讨论】:

    标签: spring-boot testing junit get-mapping


    【解决方案1】:

    使用 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
      }
    }
    

    编辑:在此处添加指向我的类似答案的链接供您参考Spring 5 with JUnit 5 + Mockito - Controller method returns null

    【讨论】:

    • 我开始测试我的 get() 方法,该方法返回所有 UserDto,但我仍然做错了什么,你能检查一下吗? link
    • 代码和错误消息看起来不同步。在 pl.rmitula.restfullshop.controller.UserControllerTest.getAll(UserControllerTest.java:40) 行号。是 40,根据代码,第 40 行有 String url = "/api/users",不能为空。能告诉我第 40 行有什么代码吗?
    猜你喜欢
    • 2018-07-31
    • 2017-03-10
    • 2019-03-27
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-18
    相关资源
    最近更新 更多