【问题标题】:Test Spring boot rest api but output not excepted测试Spring boot rest api但输出不例外
【发布时间】:2022-01-25 11:35:41
【问题描述】:

我刚刚了解了 spring 模拟测试并在 maven 测试和 eclipse IDE 中使用 spring mocktest 运行了一个简单的 rest api 应用程序,但我的输出是 400,但我的 api 在 PostMan 和 reactjs 中运行正常,我也使用安全性,但我不认为我应该在这里

这是我的 api 控制器

趋势

///my DI
@Autowired
    private BlogService blogService;
    @Autowired
    private TypeService typeService; 

@GetMapping("/trending")
    @JsonView(BlogView.List.class)
    public ResponseEntity<?> blogTrending(@RequestParam int start, @RequestParam int size,
                                          @RequestParam String sort) {
        Page<Blog> blogs = blogService.findAll(sort, size, start, "statView");
        return ResponseEntity.ok(pageToJson(blogs));
   }


 private Map<String, Object> pageToJson(Page<Blog> blogs) {
        List<BlogDTO> listBlog = ObjectMapperUtils.mapAll(blogs.getContent(), BlogDTO.class);
        return new HashMap<String, Object>() {/**
             * 
             */
            private static final long serialVersionUID = 1L;

        {
            put("blogs", listBlog);
            put("size", blogs.getTotalPages());
            put("page", blogs.getNumber());
        }};
    }

这是我的测试课

@WebMvcTest(BlogController.class)
public class BlogControllerTesting {

    @MockBean
    private BlogService blogService;

    @MockBean
    private TypeService typeService;

    @MockBean
    private AccountService accountService;

    @MockBean
    private JwtUtils jwtUtils;

    @MockBean
    private JwtEntryPoint entryPoint;

    @Autowired
    private MockMvc mockMvc;

    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(get("/api/blog/trending?start=0&size=5&sort=ASC")).andDo(print())
                .andExpect(status().isOk());
    }
}

我运行测试时的输出

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/blog/trending
       Parameters = {start=[0], size=[5], sort=[ASC]}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.springboot.app.controller.BlogController
           Method = com.springboot.app.controller.BlogController#blogTrending(int, int, String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = java.lang.NullPointerException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /api/blog/trending
       Parameters = {start=[0], size=[5], sort=[ASC]}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = com.springboot.app.controller.BlogController
           Method = com.springboot.app.controller.BlogController#blogTrending(int, int, String)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = java.lang.NullPointerException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 400
    Error message = null
          Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

其他信息

【问题讨论】:

  • 400(bad request,在spring-mvc中)通常意味着:错误的内容类型(,错误的参数),请与邮递员(请求)标头比较!

标签: spring-boot mockito spring-test


【解决方案1】:

你完全模拟了 BlogService,所以 blogservice.findAll() 返回 null,所以当你调用 pageToJson 时,blogs.getContent() 会抛出 NullPointerException

模拟 blogService.findAll() 以返回一些实际值:

Mockito.when(blogService.findAll(any()).thenReturn(new Page<Blog>());

... 或扩展 pageToJson 方法来处理 null 值。 (取决于findAll方法是否可以返回null

private Map<String, Object> pageToJson(Page<Blog> blogs) {
  if (blogs==null) {
    return Collections.<String, Object>emptyMap();
  }
  ...

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2017-04-23
    • 2016-11-28
    • 2017-11-02
    • 2019-08-24
    • 2022-01-04
    • 2019-07-18
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多