美文网首页
SpringBoot使用MockMVC单元测试

SpringBoot使用MockMVC单元测试

作者: 皮多堡 | 来源:发表于2018-08-20 18:10 被阅读0次
package com.hp.backend.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hp.core.entity.User;
import org.junit.Before;
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.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;

/**
 * @author haopeng
 * @date 2018-08-20 15:27
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
@WebAppConfiguration
public class TestControllerTest {

    private MockMvc mvc;

    @Autowired
    private WebApplicationContext context;

    @Before
    public void setUp() {
        mvc = MockMvcBuilders.webAppContextSetup(context).build();
    }

    @Test
    public void get() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/swagger"))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().string("hello swagger ..."));

    }


    @Test
    public void post() throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User();
        user.setPhoneNum("258963");
        user.setName("hawawa");
        mvc.perform(MockMvcRequestBuilders.post("/post")
                .contentType(MediaType.APPLICATION_JSON_UTF8)
                .content(mapper.writeValueAsString(user)))
                .andDo(print())
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andExpect(MockMvcResultMatchers.jsonPath(
                        "phoneNum").value("123456"))
                .andExpect(MockMvcResultMatchers.jsonPath(
                        "username").value("peng"));
    }

}

相关文章

网友评论

      本文标题:SpringBoot使用MockMVC单元测试

      本文链接:https://www.haomeiwen.com/subject/ytoliftx.html