본문 바로가기
개발/웹

[SPRING-BOOT] controller junit test

by 로그인시러 2016. 11. 29.
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {SpringJunitApplication.class, TestConfig.class})
@WebAppConfiguration
@IntegrationTest("server.port=8888")
public class UserControllerTest {
 
    private User user;
 
    @Autowired private UserRepository userRepository;
    @Autowired private WebApplicationContext wac;
    @Autowired private ObjectMapper objectMapper;
    private MockMvc mock;
 
    @Before
    public void setUp() throws Exception {
        this.mock = MockMvcBuilders.webAppContextSetup(wac).build();
        user = new User();
        user.setUsername("woniper");
    }
 
    @Test
    public void testCreateUser() throws Exception {
        ResultActions resultActions =
                mock.perform(MockMvcRequestBuilders.post("/users")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsBytes(user)));
 
        resultActions.andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isCreated())
                .andExpect(MockMvcResultMatchers.jsonPath("$.username", Matchers.is(user.getUsername())));
    }
 
    @Test
    public void testGetUserList() throws Exception {
        User createUser = userRepository.save(user);
 
        ResultActions resultActions =
                mock.perform(MockMvcRequestBuilders.get("/users"));
 
        resultActions.andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.jsonPath("$[0].userId", Matchers.is(createUser.getUserId())))
                .andExpect(MockMvcResultMatchers.jsonPath("$[0].username", Matchers.is(createUser.getUsername())));
    }
}


출처 : http://blog.woniper.net/272


'개발 > ' 카테고리의 다른 글

mybatis typealiases  (0) 2016.11.29
spring test mockmvc  (0) 2016.11.29
server, jsp, servlet version 확인  (0) 2016.11.23
forward vs redirect  (0) 2016.11.23
include directive vs include action tag  (0) 2016.11.23

댓글