mock依赖
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
<scope>test</scope>
</dependency>
package xxx;
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.status;
@RunWith(MockitoJUnitRunner.class)
public class UserApiControllerMockTest {
private MockMvc mockMvc;
@Mock
private ISysUserService iSysUserService;
@Mock
private IExtConfigparamService extConfigparamService;
@Mock
private ISmsService smsService;
@Mock
private ISmsSendService smsSendService;
@Mock
private ITMessageInfoService messageInfoService;
@InjectMocks
private UserApiController userApiController;
@Before
public void setup() {
mockMvc = MockMvcBuilders.standaloneSetup(userApiController).build();
//为加签名提供固定的返回值
when(extConfigparamService.fetchValue(Constant.SUNPLS_MD5_KEY)).thenReturn(SignUtil.MD5_KEY);
}
@After
public void setup2() {
System.out.println("excute compelet");
}
/**
* 用户登录
* 被模拟的方法:iSysUserService.queryByEmail(?)
* 测试完成
* 只适用于系统管理员登录
* @throws Exception
*/
@Test
public void testLogin() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("mobile", "admin");
map.put("password", RSATool.encrypt("admin"));
map.put("sign_type", "MD5");
String sign = SignUtil.addSign(JSON.parseObject(JsonUtils.objectToJson(map)), SignUtil.MD5_KEY);
map.put("sign", sign);
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
SysUser user=new SysUser();
user.setNickname("系统管理员");
user.setId("1");
user.setEmail("admin");
user.setPwd("21232F297A57A5A743894A0E4A801FC3");
//为被Mock注解过的方法提供一个固定的返回
when(iSysUserService.queryByEmail("admin")).thenReturn(user);
//将原有的SecurityUtil中的SecurityManager替换掉,换成自定义的ini文件
securityManager();
// mock测试模块
MvcResult result=mockMvc
.perform(get("/api/user/login.do").contentType(MediaType.APPLICATION_JSON).content(reqstr))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.user_info.user_id").value("1"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("用户: admin登录成功")) //接口 value("登录成功"))
.andReturn();
System.out.println(result.getResponse().getContentAsString());
}
/**
* 发送短信验证码
* 被模拟的方法:smsService.sendSms(?)
* 测试完成
*/
@Test
public void testGetChangePwdSms(){
Map<String, Object> map = new HashMap<>();
map.put("mobile", "18658178691");
map.put("sign_type", "MD5");
String sign = SignUtil.addSign(JSON.parseObject(JsonUtils.objectToJson(map)), SignUtil.MD5_KEY);
map.put("sign", sign);
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
try {
when(smsService.sendSms("18658178691")).thenReturn(30);
String responseString = mockMvc
.perform(get("/api/user/getChangePwdSms.do").contentType(MediaType.APPLICATION_JSON).content(reqstr))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.duration").value("30"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("发送成功")) //接口 success
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 测试重置登录密码
* 被模拟的方法:smsService.isCodeValid(?,?)
* 测试完成
* @throws Exception
*/
@Test
public void testResetLoginPwd() throws Exception{
Map<String, Object> map = new HashMap<>();
map.put("mobile", "18658178691");
map.put("new_login_pwd", RSATool.encrypt("admin"));
map.put("sms_code", "201738");
map.put("sign_type", "MD5");
String sign = SignUtil.addSign(JSON.parseObject(JsonUtils.objectToJson(map)), SignUtil.MD5_KEY);
map.put("sign", sign);
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
when(smsService.isCodeValid("18658178691", "201738")).thenReturn(true);
//when(iSysUserService.updatePassword("18658178691", "21232F297A57A5A743894A0E4A801FC3"));
String responseString = mockMvc
.perform(get("/api/user/resetLoginPwd.do").contentType(MediaType.APPLICATION_JSON).content(reqstr))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("修改成功")) // 接口 success
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
}
/**
* 测试修改密码
* 测试完成
* @throws Exception
*/
@Test
public void testUpdatePassword() throws Exception{
Map<String, Object> map = new HashMap<>();
map.put("old_password", RSATool.encrypt("123456"));
map.put("new_password", RSATool.encrypt("admin"));
map.put("sign_type", "MD5");
String sign = SignUtil.addSign(JSON.parseObject(JsonUtils.objectToJson(map)), SignUtil.MD5_KEY);
map.put("sign", sign);
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
//when(iSysUserService.modifyPassword("admin", MethodUtil.MD5("123456"), MethodUtil.MD5("admin")));
String responseString = mockMvc
.perform(get("/api/user/updatePassword.do")
.contentType(MediaType.APPLICATION_JSON)
.content(reqstr).session(((MockHttpSession)getLoginSession())))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("修改成功")) // 接口 success
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
}
/**
* 测试退出登录
* 测试完成
* @throws Exception
*/
@Test
public void testLogout() throws Exception{
Map<String, Object> map=new HashMap<>();
map.put("sign_type", "MD5");
String sign = SignUtil.addSign(JSON.parseObject(JsonUtils.objectToJson(map)), SignUtil.MD5_KEY);
map.put("sign", sign);
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
securityManager();
String responseString = mockMvc
.perform(get("/api/user/logout.do")
.contentType(MediaType.APPLICATION_JSON)
.content(reqstr))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("退出成功")) // 接口 success
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
}
@Test
public void testMyMsg() throws Exception{
ArrayList<MessageResultVO> list = new ArrayList<>();
MessageResultVO result = new MessageResultVO();
result.setId("1");
result.setCreate_time(new Date());
result.setMsg("您有一条信息");
list.add(result);
when(messageInfoService.queryByUserId("1")).thenReturn(list);
Map<String, Object> map=new HashMap<>();
String reqstr = JsonUtils.objectToJson(map);
securityManager();
String responseString = mockMvc
.perform(get("/api/user/myMsg.do")
.contentType(MediaType.APPLICATION_JSON)
.content(reqstr)
.session(((MockHttpSession)getLoginSession())))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("success"))
.andExpect(MockMvcResultMatchers.jsonPath("$.data.msg_list[0].msg").value("您有一条信息"))
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
}
@Test
public void testSmsSend() throws Exception, Exception{
Map<String, Object> map=new HashMap<>();
map.put("id", "32D829IS93RR82A9IR554HS");
map.put("data", "{\"account\":\"6391\",\"income\":\"100\",\"balance\":\"100\"}");
map.put("mobile", "18658178691");
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
when(smsSendService.getSmsContent(Mockito.anyMap())).thenReturn("您的账户为4332,成功转入1000元,您的余额为1000元");
when(smsSendService.sendMsgBank(Mockito.anyMap())).thenReturn(true);
String responseString = mockMvc
.perform(get("/api/user/sendmessage.do")
.contentType(MediaType.APPLICATION_JSON)
.content(reqstr))
.andExpect(status().isOk())
.andExpect(MockMvcResultMatchers.jsonPath("$.code").value("000000"))
.andExpect(MockMvcResultMatchers.jsonPath("$.msg").value("Success")) // 接口 success
.andReturn().getResponse().getContentAsString();
System.out.println(responseString);
}
/**
* 将shiro由applicationContext-shiro.xml文件加载转化为加载本地shiro.ini
* @return
*/
public Subject securityManager(){
Factory<SecurityManager> factory=new IniSecurityManagerFactory("classpath:shiro.ini");
SecurityManager securityManager=factory.getInstance();
SecurityUtils.setSecurityManager(securityManager);
Subject subject=SecurityUtils.getSubject();
return subject;
}
/**
* 将模拟出来的登录及其数据放入session当中
* @return
* @throws Exception
*/
public HttpSession getLoginSession() throws Exception{
Map<String, Object> map = new HashMap<>();
map.put("mobile", "admin");
map.put("password", RSATool.encrypt("admin"));
map.put("sign_type", "MD5");
String sign = SignUtil.addSign(JSON.parseObject(JsonUtils.objectToJson(map)), SignUtil.MD5_KEY);
map.put("sign", sign);
String reqstr = JsonUtils.objectToJson(map);
System.out.println(reqstr);
SysUser user=new SysUser();
user.setNickname("系统管理员");
user.setId("1");
user.setEmail("admin");
user.setPwd("21232F297A57A5A743894A0E4A801FC3");
//为被Mock注解过的方法提供一个固定的返回
when(iSysUserService.queryByEmail("admin")).thenReturn(user);
//将原有的SecurityUtil中的SecurityManager替换掉,换成自定义的ini文件
securityManager();
// mock测试模块
MvcResult result=mockMvc
.perform(get("/api/user/login.do").contentType(MediaType.APPLICATION_JSON).content(reqstr))
.andExpect(status().isOk()).andReturn();
HttpSession session=result.getRequest().getSession();
session.setAttribute("session_user", user);
return session;
}
}