jeudi 10 septembre 2020

Why the controller method returns void content of response in the test method?

I'm learning Java Spring and trying to write a test of a controller method. That is, I want to perform a controller method by its path and check if the returning content contains some sequence of symbols. For example, my test is invoking a content on the page by address "user/1" and expecting that content will contain "root".

Unfortunately, performing "user/1" returns null content, although it's possible to input this route in a browser and get a page of this user without any problems.

Here is my controller method that I want to test

@GetMapping("/{id}")
    public String view(@PathVariable(value = "id") Integer id, Model model) throws EntityNotFoundException {
        try {
            User item = users.get(id);
            model.addAttribute("item", item);
            model.addAttribute("posts", posts.getLatestByUser(item, 10));
            model.addAttribute("comments", comments.getLatestByUser(item, 10));
            return "user/view";
        } catch (IllegalArgumentException ex) {
            throw new EntityNotFoundException("Cannot find a user with id = " + id);
        }
    }

here is my class for testing

@SpringBootTest(classes = {
        Main.class,
        TestDataConfig.class,
        TestWebConfig.class
})
@ActiveProfiles("test")
@AutoConfigureMockMvc
@Sql(value = {"/create-tables.sql", "/fill-tables.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
public class UserCtrlTest {

    @Autowired
    private UserCtrl controller;

    @Autowired
    private MockMvc mockMvc;

    @Test
    @WithAnonymousUser
    public void shouldDisplayUserInfoUponWatchingUserPage() throws Exception {
        MvcResult result = this.mockMvc.perform(get("/user/1"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(view().name("user/view"))
                .andReturn();

        String stringResult = result.getResponse().getContentAsString();
        Assert.assertTrue(stringResult.contains("<h4>root</h4>"));
    }
}

Here is my view resolver class

@Bean
    public ViewResolver viewResolver() {
        InternalResourceViewResolver bean = new InternalResourceViewResolver();
        bean.setViewClass(JstlView.class);
        bean.setPrefix("/WEB-INF/views/");
        bean.setSuffix(".jsp");
        return bean;
    }

Here is result that the method .andDo(print()) returns in the console

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /user/1
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = ru.job4j.forum.controller.UserCtrl
           Method = ru.job4j.forum.controller.UserCtrl#view(Integer, Model)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = user/view
             View = null
        Attribute = item
            value = ru.job4j.forum.model.User@20
           errors = []
        Attribute = posts
            value = [ru.job4j.forum.model.Post@20, ru.job4j.forum.model.Post@21]
        Attribute = comments
            value = [ru.job4j.forum.model.Comment@21, ru.job4j.forum.model.Comment@24]
        Attribute = user
            value = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Language:"en", 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 = /WEB-INF/views/user/view.jsp
   Redirected URL = null
          Cookies = []

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /user/1
       Parameters = {}
          Headers = []
             Body = null
    Session Attrs = {}

Handler:
             Type = ru.job4j.forum.controller.UserCtrl
           Method = ru.job4j.forum.controller.UserCtrl#view(Integer, Model)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = user/view
             View = null
        Attribute = item
            value = ru.job4j.forum.model.User@20
           errors = []
        Attribute = posts
            value = [ru.job4j.forum.model.Post@20, ru.job4j.forum.model.Post@21]
        Attribute = comments
            value = [ru.job4j.forum.model.Comment@21, ru.job4j.forum.model.Comment@24]
        Attribute = user
            value = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Language:"en", 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 = /WEB-INF/views/user/view.jsp
   Redirected URL = null
          Cookies = []

Could you help me to understand why the request doesn't return the content of the page? And how to solve this problem? If you need other sources and screenshots to clarify the situation, please, write about that and I will add them.

Aucun commentaire:

Enregistrer un commentaire