Junit对springMVC controller层测试

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

@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());//打印对应的请求和数据到控制台

    }

 

}

posted @ 2017-04-26 15:22  tl-forever  阅读(112)  评论(0)    收藏  举报