单元测试代码如下:
import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration("/META-INF/test-servlet-context.xml") public class RechargeControllerTest{ @Autowired private MobileNoAttrService mobileNoAttrService; @Autowired private RechargeController rechargeController; private MockMvc mockMvc; @Before public void setup() { this.mockMvc = MockMvcBuilders.standaloneSetup(rechargeController).build(); MobileNoAttr mobileNoAttr=new MobileNoAttr(); mobileNoAttr.setProvince("新疆"); mobileNoAttr.setCity("乌鲁木齐"); mobileNoAttr.setAreaCode("0991"); mobileNoAttr.setMobileType("中国移动"); mobileNoAttr.setMobileNo("1390000"); when(mobileNoAttrService.queryMobileNoAttr("1390000")).thenReturn(null); when(mobileNoAttrService.queryMobileNoAttrFromOut("1390000")).thenReturn(mobileNoAttr); } @Test public void testMakeOrder() throws Exception { this.mockMvc.perform(get("/makeOrder").param("mobileNo", "13900008888").param("faceValue", "100") .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))) .andExpect(status().isOk()) .andExpect(jsonPath("$.resCode").value("1000")); } } |
get方法返回的是一个request的构造器,你可以通过这个对象往request 或者session中设置值。
配置文件内容如下:
<bean id="mobileNoAttrService" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="tengfei.service.MobileNoAttrService"/> </bean> <bean id="interMsgService" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="tengfei.service.InterMsgService"/> </bean> <bean id="userService" class="org.mockito.Mockito" factory-method="mock"> <constructor-arg value="tengfei.service.UserService"/> </bean> <context:component-scan base-package="tengfei.controller" /> |
这个单元测试的方法能够模拟你发请求调用controller接口,当然他并不是真的发起http请求
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |