SPRINGBOOT-使用springboot-junit测试controller层接口

需求:
使用springboot junit测试所有controller层的接口

方法:
通过Mock方式实现

步骤:
1.创建MockMvc实例,对应代码如下:
  private MockMvc mvc;
  
  @Autowired
  private WebApplicationContext wac;
  
  @Before
  public void setUp()

  {

mvc = MockMvcBuilders.webAppContextSetup(wac).build();

  }

2.使用MockMvc实例发送请求,对应代码如下:
  发送get请求:
  RequestBuilder request = get(controller接口方法对应url); 
  mvc.perform(request)

  发送post请求:
  RequestBuilder request = post(controller接口方法对应url).content(参数内容);
  mvc.perform(request)

注:
1.要测试所有controller层接口,需要以WebApplicationContext实例作为参数来创建MockMvc实例
2.使用静态get、post方法需要手工导入对应的类:
  import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
  import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

猜你喜欢

转载自blog.csdn.net/ignorewho/article/details/80620658