Controller单元测试——springboot中使用

一,使用方法

很长一段时间的单元测试都只是针对service和dao层,对于controller接口的测试如果是get方法可以运行项目在浏览器中直接访问接口地址;如果是post方法就比较麻烦了,还要自己写个js来传输json数据,后来发现可以直接在单元测试中加上controller接口的测试,方便了很多。具体如下:

Controller中的方法 requestMapping中使用name="/saveAdmin"无法识别

    @RequestMapping("/getUser")
	@ResponseBody
	public String getUser(HttpServletRequest request,HttpServletResponse response) {
		String userIdStr=request.getParameter("userId");
		logger.info("userId="+userIdStr);
		logger.info("boot run");
		return "user";
	}


    @RequestMapping(value="/saveAdmin", method=RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveAdmin(@Valid @RequestBody Admin admin,BindingResult result, RespModel resp) {
		MsgEnum msg=adminService.saveAdmin(admin);
		return resp.setRespEnum(msg);
				
	}

单元测试中的内容 

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class MybatisTest {

	@Autowired
    private WebApplicationContext wac;
    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build(); //初始化MockMvc对象
    }

    @Test
    public void getUsers() throws Exception {
//        mockMvc.perform(MockMvcRequestBuilders.post("/user/getUser")
//                .accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());
        
                String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/user/getUser")    //请求url,请求的方式是get
        		.contentType(MediaType.APPLICATION_FORM_URLENCODED)  //请求的数据格式
        		.param("userId","1"))   //添加参数
		.andExpect(status().isOk())     //返回的状态是200
		.andDo(print())         		//打印出请求和响应的内容
		.andReturn().getResponse().getContentAsString();   //将响应的数据转换为字符串
        System.out.println("responseString = " + responseString);
    }
    
    @Test
    public void saveAdmin() throws Exception {
    	Admin admin=new Admin();
    	admin.setUserId(222);    	
    	String jsonObject=JSONObject.fromObject(admin).toString();
    	System.out.println(jsonObject);
        mockMvc.perform(MockMvcRequestBuilders.post("/user/saveAdmin").content(jsonObject)
                .contentType(MediaType.APPLICATION_JSON))
        .andExpect(status().isOk())        
        .andDo(print()).andReturn().getResponse().getContentAsString();
    }
}

*.contentType(MediaType.APPLICATION_JSON)可以正常运行 如果是accept(MediaType.APPLICATION_JSON)会报如下异常

Resolved exception caused by handler execution: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/octet-stream' not supported

 

二,为了方便使用,对其进行封装 BaseControllerTest.java

@RunWith(SpringRunner.class)
@SpringBootTest
@Slf4j
public class BaseControllerTest {
	@Autowired
    private WebApplicationContext context;
    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); //初始化MockMvc对象
    }
    
    
    public String doPost(String url,String jsonObject) throws Exception {
    	ResultActions result=mockMvc.perform(MockMvcRequestBuilders.post(url).content(jsonObject)
                 .contentType(MediaType.APPLICATION_JSON));    	   				        
        return doPrint(result);
    }
    
    public String doGet(String url,Map<String,String> param) throws Exception {
    	MockHttpServletRequestBuilder mockBuilder=MockMvcRequestBuilders.get(url)    //请求url,请求的方式是get
		.contentType(MediaType.APPLICATION_FORM_URLENCODED);  //请求的数据格式
    	if(param!=null&&param.size()>0) {
    		for(Map.Entry<String, String> entry:param.entrySet()) {
    			mockBuilder.param(entry.getKey(), entry.getValue());
    		}    		
    	}
    	ResultActions result=mockMvc.perform(mockBuilder);
    	return doPrint(result);
    }
    //处理返回结果
    public String doPrint(ResultActions result) throws Exception {
    	String responseDate=result.andExpect(status().isOk())     //返回的状态是200
    			.andDo(print())         		//打印出请求和响应的内容
    			.andReturn().getResponse().getContentAsString();   //将响应的数据转换为字符串
    	System.out.println("responseDate="+responseDate);
    	return responseDate;
    }
}

test调用 UserControllerTest.java

public class UserControllerTest extends BaseControllerTest{

	@Test
	public void testAddAdmin() throws Exception {
		Admin admin=new Admin();
    	admin.setUserId(222);
    	admin.setFlag(1);
    	String jsonObject=JSONObject.fromObject(admin).toString();
    	System.out.println(jsonObject);
		String result=super.doPost("/user/saveAdmin", jsonObject);
	}
	
	@Test
	public void testGetAdmin() throws Exception {
	    	    	
		String result=super.doGet("/user/getAdmin", null);
	}
}

这样以后使用就简洁多了。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值