Junit对springMVC controller层测试

大憨熊 提交于 2020-04-07 16:03:17

//指定使用的单元测试执行类

@RunWith(SpringRunner.class)

@WebAppConfiguration

//指定spring配置文件的指定路径,需要所有spring配置文件全部加载

@ContextConfiguration("test-servlet-context.xml")

public class ExampleTests {

 

    //容器

    @Autowired

    private WebApplicationContext wac;

   

    //MockMvc是springMVC提供的controller测试类

    private MockMvc mockMvc;

 

    //setup方法在每个方法执行之前都会执行,加载配置文件

    @Before

    public void setup() {

        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

    }

 

    @Test

    public void getAccount() throws Exception {

     // get("/accounts/1")请求的URL,get请求

   this.mockMvc.perform(get("/accounts/1").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))//数据格式

            .andExpect(status().isOk())//断言返回状态

            .andExpect(content().contentType("application/json"))//断言contentType

            .andExpect(jsonPath("$.name").value("Lee"))//断言json中key为name的value是否为Lee

    .andDo(print());//打印对应的请求和数据到控制台

    }

 

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!