2017-12-08 9 views
0

버전 테스트 중에는 http://www.baeldung.com/spring-boot-testing 의 정보를 기반으로하는 UserController에 대한 테스트를 작성했습니다. 어떻게 사용자와 기록을 수신했는지 확인하기 위해 주석 처리 된 회선을 변경할 수 있습니까? 또는이 사례에 대해 어디에서 읽을 수 있습니까? 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 = [] 
+0

당신이 저에게 당신이 원하는 결과 예를 들어 줄 왜 당신이 사용되어야한다 스프링 부팅에 JSP를 사용할 수 있습니다 사용하여 값을 예상했다 확인할 수 있습니다 https://spring.io/guides/gs/serving-web-content/ – Osgux

답변

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