最近使用Mockito完成了几个简单的测试,写个博客mark一下:
第一种模拟web请求
@SpringBootTest @RunWith(SpringRunner.class) @WebAppConfiguration //测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根 public class ControllerTest { private static final Logger logger = LogManager.getLogger(ControllerTest.class); @Autowired private WebApplicationContext context; @Mock private UserInfoService userInfoService; private MockMvc mockMvc; /** * 构造MockMvc * @throws Exception */ @Before public void setupMockMvc() throws Exception { // 初始化Mock MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.webAppContextSetup(context).build(); } /** * 模拟add请求 */ @Test public void insertUserInfoTest() { UserInfo userInfo = initUserInfo(); when(userInfoService.insert(any())).thenReturn(1); logger.info("++++++++++++++++++++++++++" + userInfo.toString()); // 调用接口,传入添加的用户参数 try{ String response = mockMvc.perform(post("/userInfo/add").contentType(MediaType.APPLICATION_JSON) .content(userInfo.toString()).header("SESSIONNO", "EA60F3C2C7384DBA8A7B8B114474DC12")) .andReturn().getResponse().getContentAsString(); logger.info("******************" + response); }catch (Exception e) { e.printStackTrace(); } } @Test public void addTest() { try { // 1. controller mvc test MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/userInfo/add")) .andExpect(MockMvcResultMatchers.handler().handlerType(UserInfoController.class)) .andExpect(MockMvcResultMatchers.handler().methodName("addUserInfo")) // .andExpect(MockMvcResultMatchers.view().name("demo/hello")) // .andExpect(MockMvcResultMatchers.model().attributeExists("msg")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); // Assert.assertNotNull(result.getModelAndView().getModel().get("msg")); }catch (Exception e) { e.printStackTrace(); } } /** * 模拟update测试 */ @Test public void updateUserInfo() { try{ // String response = mockMvc.perform(post("/user/updateUser").contentType(MediaType.APPLICATION_JSON) // .content(userInfo.toString()).header("SESSIONNO", "EA60F3C2C7384DBA8A7B8B114474DC12")) // .andReturn().getResponse().getContentAsString(); // logger.info("update****" + response); }catch (Exception e) { e.printStackTrace(); } } private UserInfo initUserInfo() { UserInfo userInfo = new UserInfo(); userInfo.setBirthday(new Timestamp(System.currentTimeMillis())); userInfo.setCreateTime(new Timestamp(System.currentTimeMillis())); userInfo.setEducation(5); userInfo.setIdCardCode("********************"); userInfo.setMaritalStatus(1); userInfo.setNickName("社会主义接班人"); userInfo.setPassword(encoderByMd5("a123456")); userInfo.setPhoneNumber("************"); userInfo.setSex(1); userInfo.setStatus(1); userInfo.setUserAddress("hlxj"); userInfo.setUserEmail("**********@qq.com"); userInfo.setUserImage("图片"); userInfo.setUserName("dsc"); return userInfo; } private String encoderByMd5(String password) { //确定计算方法 String md5Password = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); BASE64Encoder base64en = new BASE64Encoder(); //加密后的字符串 md5Password = base64en.encode(md5.digest(password.getBytes("utf-8"))); logger.info(md5Password); }catch (Exception e){ e.printStackTrace(); } return md5Password; } }
第二种模拟web请求
@RunWith(SpringRunner.class) public class ServiceTest { private static final Logger logger = LogManager.getLogger(ServiceTest.class); @InjectMocks UserInfoController userInfoController; @Mock UserInfoService userInfoService; @Before public void init() { UserInfo userInfo = initUserInfo(); given(userInfoService.insert(any())).willReturn(1); given(userInfoService.selectUnique(any())).willReturn(null, userInfo); } @Test public void testAdd() { UserInfo userInfo = new UserInfo(); userInfoController.addUserInfo(userInfo); userInfo = initUserInfo(); userInfoController.addUserInfo(userInfo); } @Test public void getUserInfoTest() { UserInfo userInfo = new UserInfo(); logger.info("测试1*** " + userInfoController.getUserInfo(userInfo)); userInfo.setId(3L); logger.info("测试2*** " + userInfoController.getUserInfo(userInfo)); } private UserInfo initUserInfo() { UserInfo userInfo = new UserInfo(); userInfo.setBirthday(new Timestamp(System.currentTimeMillis())); userInfo.setCreateTime(new Timestamp(System.currentTimeMillis())); userInfo.setEducation(5); userInfo.setIdCardCode("********************"); userInfo.setMaritalStatus(1); userInfo.setNickName("社会主义接班人"); userInfo.setPassword(encoderByMd5("a123456")); userInfo.setPhoneNumber("************"); userInfo.setSex(1); userInfo.setStatus(1); userInfo.setUserAddress("hlxj"); userInfo.setUserEmail("**********@qq.com"); userInfo.setUserImage("图片"); userInfo.setUserName("dsc"); return userInfo; } private String encoderByMd5(String password) { //确定计算方法 String md5Password = null; try { MessageDigest md5 = MessageDigest.getInstance("MD5"); BASE64Encoder base64en = new BASE64Encoder(); //加密后的字符串 md5Password = base64en.encode(md5.digest(password.getBytes("utf-8"))); logger.info(md5Password); }catch (Exception e){ e.printStackTrace(); } return md5Password; } }
以上两种只是我的个人测试,由于刚刚开始试验,对于一些细节还不是熟悉,期待日后修改。。。