检查Spring Boot Test Controller中的数据

时间:2017-12-08 20:49:45

标签: java spring spring-mvc testing spring-boot

我为我的UserController编写了一个基于http://www.baeldung.com/spring-boot-testing信息的测试 在版本测试过程中。如何更改注释行以检查收到了哪些用户和记录?或者我在哪里可以阅读这个案例? 基于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 = null

Resolved Exception:
         Type = null

ModelAndView:
    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 = null

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

1 个答案:

答案 0 :(得分:0)

您可以使用org.hamcrest.Matchers

检查模型属性是否存在并具有预期值
public void welcome() throws Exception {
        // Mock required services

        this.mvc.perform(get("/")
                .contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(status().isOk())
                .andExpect(model().attribute("user", Matchers.hasProperty("username", Matchers.equalTo("pavelkuropatin"))))
                .andExpect(model().attribute("records", Matchers.hasSize(3)))
        ;
    }