mockMvc测试案例

使用mockMvc可模拟http请求,在不启动服务的情况进行快速测试。

package junit;


import java.util.concurrent.TimeUnit;

import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.ResultActions;
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;

@WebAppConfiguration
public class ControllerTestJuint extends BaseJunit{
    protected MockMvc mockMvc;
    @Autowired
    protected WebApplicationContext wac;
    @Before()  //这个方法在每个方法执行之前都会执行一遍
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //初始化MockMvc对象
    }
    @Test
    public void mockTest() throws Exception{
       ResultActions reaction =this.mockMvc.perform(MockMvcRequestBuilders.post("/sys/out/mockTest")
               .contentType(MediaType.APPLICATION_JSON)//请求体时json
               .param("customerId","7")
               .param("serviceType","all_service")
               .param("params[company_id]","1110000")//组装map对象
               .param("params[AGE]","0,5")
               );
       reaction.andExpect(MockMvcResultMatchers.status().isOk());
       MvcResult mvcResult =reaction.andReturn();
       System.out.println(mvcResult.getResponse().getContentAsString());
       TimeUnit.SECONDS.sleep(60*60);
    }
}

package junit;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:applicationContext_*_test.xml"})
@Transactional
public class BaseJunit {

}

使用param方法添加参数,map参数以 ("map[mapkey]","mapvalue") 格式添加参数。

后台接受的controller:

    @RequestMapping(value="/mockTest",method = RequestMethod.POST)
    @ResponseBody
    public BaseMassage customerCreate(Dao dao){
        BaseMassage baseMassage = new BaseMassage();
        try{
            if (StringUtils.isEmpty(dao.getCustomerId())) {
                
            }else if(StringUtils.isEmpty(dao.getServiceType())){
               
            }else if(StringUtils.isEmpty(dao.getParams().get("company_id"))){
  
            }else{

            }
        }catch(Exception e){
        }
        return baseMassage;
    }

Dao:

@Setter
@Getter
public
class Dao { private String customerId; private String serviceType; private Map<String, String> params; }

 

posted @ 2019-10-28 17:18  笔记Next  阅读(1204)  评论(0编辑  收藏  举报