0

i just learn about spring mock test and run a simple rest api app with spring mocktest in maven test and eclipse IDE, but my output is 400 but my api run ok in PostMan and reactjs, i use security too but i dont think i should it here

here is my api controller

Trending

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

here is my test class

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

my output when i running test

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 = []

another information

enter image description here

Lesiak
  • 22,088
  • 2
  • 41
  • 65
  • 400 (bad request, in spring-mvc) often means: wrong content type(, wrong parameters), please compare with postman (request) headers! – xerx593 Dec 25 '21 at 11:59

1 Answers1

0

You mock BlogService completely, so blogservice.findAll() return null, so when you call pageToJson, the blogs.getContent() throws NullPointerException.

Mock the blogService.findAll() to return some real value:

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

... or extend the pageToJson method to handle null value. (depends on whether findAll method can return null or not.

private Map<String, Object> pageToJson(Page<Blog> blogs) {
  if (blogs==null) {
    return Collections.<String, Object>emptyMap();
  }
  ...
Selindek
  • 3,269
  • 1
  • 18
  • 25