Pavel Kuropatin спросил: 14 ноября 2017 в 07:09 в: java

Я написал тест для своего UserController, основанный на информации с http://www.baeldung.com/spring-boot-testingIn во время прохождения теста версии. Как я могу изменить закомментированную строку, чтобы проверить, какой пользователь и записи были получены? Или где я могу прочитать об этом случае? Шаблоны на основе JSP.

@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
    model.addAttribute("user", userService.findByUsername(SecurityContextHolder.getContext().getAuthentication().getName()));
    model.addAttribute("records", recordService.findAll());
    return "welcome";
}


package pavelkuropatin.web;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import pavelkuropatin.WebApplicationClass;
import pavelkuropatin.entities.Record;
import pavelkuropatin.entities.User;
import pavelkuropatin.service.RecordService;
import pavelkuropatin.service.SecurityService;
import pavelkuropatin.service.UserService;
import pavelkuropatin.validator.UserValidator;
import java.util.Arrays;
import static org.mockito.Mockito.anyString;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringRunner.class)
@SpringBootTest(
    classes = WebApplicationClass.class)
@AutoConfigureMockMvc
@TestPropertySource(
    locations = "classpath:application.properties")
public class UserControllerTest {    @MockBean
    public UserService userService;
    @MockBean
    public RecordService recordService;
    @MockBean
    public SecurityService securityService;
    @MockBean
    public UserValidator userValidator;
    @Autowired
    private MockMvc mvc;    @Test
    public void welcome() throws Exception {
        Record record1 = new Record();
        record1.setId(1L);
        record1.setTopic("Topic1");
        record1.setText("Text1");
        Record record2 = new Record();
        record2.setId(2L);
        record2.setTopic("Topic2");
        record2.setText("Text2");
        User user = new User();
        user.setUsername("pavelkuropatin");
        when(userService.findByUsername(anyString())).thenReturn(user);
        when(recordService.findAll()).thenReturn(Arrays.asList(record1,     record2));
        this.mvc.perform(get("/")
            .contentType(MediaType.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk())
            //.andExpect( jsonPath("$.ModelAndView.user.username", is("pavelkuropatin")))
            //.andExpect(jsonPath("$", hasSize(3)))
        ;
    }
}

эта информация отображается в консоли.

MockHttpServletRequest:
  HTTP Method = GET
  Request URI = /
   Parameters = {}
      Headers = {Content-Type=[application/json;charset=UTF-8]}Handler:
         Type = pavelkuropatin.web.UserController
       Method = public java.lang.String pavelkuropatin.web.UserController.welcome(org.springframework.ui.Model)Async:
Async started = false
 Async result = nullResolved Exception:
         Type = nullModelAndView:
    View name = welcome
         View = null
    Attribute = user
        value = User{id=null, fio='null', username='pavelkuropatin', password='null', passwordConfirm='null', roles=null}
       errors = []
    Attribute = records
        value = [Record{id=1, text='Text1', topic='Topic1', date=null, author='null'}, Record{id=2, text='Text2', topic='Topic2', date=null, author='null'}]FlashMap:
       Attributes = nullMockHttpServletResponse:
           Status = 200
    Error message = null
          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 = /welcome.jsp
   Redirected URL = null
          Cookies = []

0 ответов