samedi 28 septembre 2019

Spring Controller Testing Added Objects NullPointerException

I've ran into this problem in different parts of my projects. It happens whenever there's a list being initialized in the controller itself, and I can't seem to understand how to mock it for the test.

I tried to instantiate the list inside of the test, add values to it.

given(user.getOrderList()).willReturn(userOrderList)

I also tried passing it as a flashAttr, requestAttr to the mockMvc.

This is the method I'm trying to test

@GetMapping("/account")
public ModelAndView account(Principal principal) {

    User user = userService.findByUsername(principal.getName());

    ModelAndView mav = new ModelAndView("profile");

    mav.addObject("user", user);
    mav.addObject("userPaymentList", user.getPaymentList());
    mav.addObject("userAddressList", user.getAddressList());
    mav.addObject("classActiveAccount", "active");

    mav.addObject("userOrderList", userOrderListSortedById(user));

    return mav;
}


private List<Order> userOrderListSortedById(User user){

    List<Order> orderList = user.getOrderList();
    orderList.sort(Comparator.comparing(Order::getId));
    Collections.reverse(orderList);

    return orderList;
}

And this is the test method

@Test
void testAccountPage() throws Exception {
    User user = new User();
    given(userService.findByUsername(anyString())).willReturn(user);

    mockMvc.perform(get("/account"))
            .andExpect(status().is3xxRedirection())
            .andExpect(model().attributeExists("userPaymentList"))
            .andExpect(model().attributeExists("userAddressList"))
            .andExpect(model().attribute("classActiveAccount", "active"))
            .andExpect(view().name("profile"));
}

I don't think the problem is with the private method, if I change the value of userOrderList to user.getOrderList(), the problem is the same.

In another method I was trying to test, I had the same problem when there was a list I could not figure out how to initialize and add the model.

if (bookList.getTotalPages() > 0) {

        List<Integer> pageNumbers = IntStream.rangeClosed(1, 
bookList.getTotalPages())
                .boxed().collect(Collectors.toList());

        mav.addObject("pageNumbers", pageNumbers);
    }

In this one, first I was failing even the check for 0, cause the list was null, and then I couldn't test pageNumbers, cause that was null.

How do I solve a problem like that?

Aucun commentaire:

Enregistrer un commentaire