@Before public void setUp() { userService = new UserServiceImpl(); userRepository = mock(UserRepository.class); userService.userRepository = userRepository; passwordEncoder = mock(PasswordEncoder.class); userService.passwordEncoder = passwordEncoder; }
@Test public void shouldReturnFalseWhenUserDisabledFailed() { user.setEnabled(false); assertFalse("should return false when given null user", userService.disable(null)); assertFalse("should return false when given disabled user", userService.disable(user)); verify(userMapper, never()).update(user); }
@Test public void shouldChangeUserPasswordWhenAsked() { User updatedUser = new User(); updatedUser.setUserName(user.getUserName()); updatedUser.setPasswordHash("newpass"); when(userMapper.findByUsername(user.getUserName())).thenReturn(updatedUser); boolean ret = userService.password(user, "newpass"); verify(userMapper).update(user); assertEquals(userService.getByUsername(user.getUserName()).getPasswordHash(), "newpass"); assertEquals(ret, true); }
@Test public void shouldReturnTrueWhenUserDisabledSuccess() { user.setEnabled(true); User disabledUser = new User(); disabledUser.setEnabled(false); disabledUser.setUserName("user"); when(userMapper.findByUsername("user")).thenReturn(disabledUser); assertTrue(userService.disable(user)); verify(userMapper).update(user); assertFalse(userService.getByUsername("user").isEnabled()); }
@Test public void shouldFindUserByEmailAndPassword() { when(userRepository.findUserByEmailAndPassword(Matchers.anyString(), Matchers.anyString())) .thenReturn(new User()); User user = service.findUserByEmailAndPassword("", ""); verify(userRepository, times(1)) .findUserByEmailAndPassword(Matchers.anyString(), Matchers.anyString()); }
@Test public void testFindOne() { User user = new User(); when(userRepository.findOne(100)).thenReturn(user); User result = userService.findOne(100); assertThat(result, is(user)); }
@Test public void testFindByNameLike() { Pageable pageable = new PageRequest(1, 10); Page<User> page = new PageImpl<User>(Arrays.asList(new User())); when(userRepository.findByNameLike("foo", pageable)).thenReturn(page); Page<User> result = userService.findByNameLike("foo", pageable); assertThat(result, is(page)); }
@Test public void testDelete() { User user = new User(); userService.delete(user); ArgumentCaptor<User> userArg = ArgumentCaptor.forClass(User.class); verify(userRepository, times(1)).delete(userArg.capture()); assertThat(userArg.getValue(), is(user)); }
@Test public void shouldNotGetAuthenticatedUserProfile() { when(authenticatedUserService.getAuthenticatedUser()).thenReturn(null); when(userRepository.findOne(Matchers.anyInt())).thenReturn(new User()); service.getAuthenticatedUserProfile(); verify(authenticatedUserService, times(1)).getAuthenticatedUser(); verify(userRepository, times(0)).findOne(Matchers.anyInt()); }
public IUser getConnectedUser() { User userSrv = session.getConnectedUser(); try { if (userSrv != null) { return UserServiceImpl.convertUser(userSrv); } else { return null; } } catch (BlogException e) { return null; } }
@Test public void shouldUpdateUserRoleWhenInvokeAuthoriseUser() { UserRole updatedUserRole = new UserRole(); updatedUserRole.setUserId(1L); updatedUserRole.setRoleName("ROLE_ADMIN"); when(userRoleMapper.get(userRole.getUserId())).thenReturn(userRole); userService.authoriseUser(userRole.getUserId()); verify(userRoleMapper).get(userRole.getUserId()); verify(userRoleMapper).update(argThat(new UserRoleMatcher(updatedUserRole))); }
/** 授权-未授权的情况下调用 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal(); User user = userService.findByUserName(shiroUser.loginName); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); for (Role role : user.getRoleList()) { // 基于Role的权限信息 info.addRole(role.getRoleName()); // 基于Permission的权限信息 info.addStringPermissions(role.getPermissions()); } // log.info(info.getRoles().toString()); return info; }
@Test public void shouldGetAuthenticatedUserProfile() { User user = new User(); user.setId(0); AuthenticatedUser authUser = new AuthenticatedUser(user); when(authenticatedUserService.getAuthenticatedUser()).thenReturn(authUser); when(userRepository.findOne(Matchers.anyInt())).thenReturn(new User()); service.getAuthenticatedUserProfile(); verify(authenticatedUserService, times(1)).getAuthenticatedUser(); verify(userRepository, times(1)).findOne(Matchers.anyInt()); }
@Test public void shouldGetAllConnections() { User user = new User(); user.setId(0); AuthenticatedUser authUser = new AuthenticatedUser(user); when(authenticatedUserService.getAuthenticatedUser()).thenReturn(authUser); when(userRepository.findAllConnectedUsers(Matchers.any(User.class))) .thenReturn(new ArrayList<User>()); service.getAllConnections(); verify(authenticatedUserService, times(1)).getAuthenticatedUser(); verify(userRepository, times(1)).findAllConnectedUsers(Matchers.any(User.class)); }
@Test public void shouldReturnAllUsersWhithRoleWhenInvoked() { List<User> users = new ArrayList<User>(); users.add(user); when(userMapper.findAllUsers()).thenReturn(users); when(userRoleMapper.get(user.getId())).thenReturn(userRole); Map<User, String> result = userService.getAllUsersWithRole(); Map<User, String> expect = new HashMap<User, String>(); expect.put(user, userRole.getRoleName()); assertEquals(result, expect); verify(userMapper).findAllUsers(); verify(userRoleMapper).get(user.getId()); }
@Test public void testSave() { User user = new User(); user.setName("foo"); when(passwordEncoder.encode("password")).thenReturn("xxxx"); userService.save(user, "password"); ArgumentCaptor<User> userArg = ArgumentCaptor.forClass(User.class); verify(userRepository, times(1)).save(userArg.capture()); User actual = userArg.getValue(); assertThat(actual, is(user)); assertThat(user.getCreatedAt(), is(notNullValue())); assertThat(user.getUpdatedAt(), is(notNullValue())); assertThat(user.getPassword(), is("xxxx")); }
/** * 方法用途和描述: 定时发送彩信任务 * * @author chenliang 新增日期:2013-10-26 * @throws ServiceException * @throws RemoteException * @since mms-task */ public void inTimeSendMmsWork() throws ServiceException, RemoteException { // 查询彩信待发送表中的数据,等级为1,渠道为web String hql = "from TbSendMmsQueue where sendLevel=1 and channel=1 and toBeSendTime is not null and states = 1"; List<TbSendMmsQueue> queueList = sendMmsQueueDAO.find(hql); try { if (null != queueList && queueList.size() > 0) { Mcp mcp = new McpServiceLocator().getMcpPort(); Gson gson = new Gson(); String param = ""; LOGGER.info("开始定时发送彩信任务."); Date now = new Date(); for (int i = 0; i < queueList.size(); i++) { TbSendMmsQueue sendMmsQueue = queueList.get(i); if (now.after(sendMmsQueue.getToBeSendTime())) { PostcardMMS cardmms = new PostcardMMS(); cardmms.setSender(sendMmsQueue.getSponsor()); // 发起人 cardmms.setReceiver(sendMmsQueue.getReciver()); // 接收人 cardmms.setContent(sendMmsQueue.getMsgBody()); // 内容 cardmms.setChannel("" + sendMmsQueue.getChannel()); // 渠道 cardmms.setMsgType(sendMmsQueue.getMsgType()); // 消息类型 cardmms.setMsgSn(sendMmsQueue.getTransationId()); // 消息id cardmms.setSubject(sendMmsQueue.getTitle()); cardmms.setImagePath(sendMmsQueue.getPicUrl()); // 图片地址 cardmms.setMusicPath(sendMmsQueue.getMusicUrl()); // 音乐地址 // 根据发起人号码,查询产品号码 TSignOrder signOrder = userService.findProductByMdn(sendMmsQueue.getSponsor()); cardmms.setProductCode(signOrder.getProductId()); // 产品id // 调用接口 param = gson.toJson(cardmms); String response = mcp.sendPostcardMms(param); Response resp = gson.fromJson(response, new TypeToken<Response>() {}.getType()); LOGGER.info("接口调用接口[" + resp.getMsg() + "]."); } } } else { LOGGER.info("没有定时发送彩信任务."); } } catch (RemoteException e) { LOGGER.error("定时发送彩信任务异常.", e); throw e; } }
/** 认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { // log.info("shiro authentication"); CustomUsernamePasswordToken token = (CustomUsernamePasswordToken) authcToken; User user = userService.findByUserName( token.getUsername()); // User [loginName=a, password=a, name=管理员1, status=1] Session session = SecurityUtils.getSubject().getSession(); if (user != null) { if ("0".equals(user.getStatus())) { throw new DisabledAccountException(); } String psw = String.valueOf(token.getPassword()); if (!psw.equals(user.getPassword())) { throw new IncorrectPasswordException("密码错误!"); } session.setAttribute("user", user); return new SimpleAuthenticationInfo( new ShiroUser(user.getLoginName(), user.getName()), user.getPassword(), getName()); } else { throw new UserNotExistException("用户不存在!"); } }
@Test public void shouldGetAllUsersAndTheirConnections() { when(userRepository.findAllUsersAndTheirConnections()).thenReturn(new ArrayList<User>()); service.getAllUsersAndTheirConnections(); verify(userRepository, times(1)).findAllUsersAndTheirConnections(); }
@Test public void shouldReturnTrueWhenPasswordCorrect() { String password = user.getPasswordHash(); assertEquals(userService.passwordVerify(user, password), true); }
@Test public void shouldReturnFalseWhenPasswordIncorrect() { String wrongPassword = "******"; assertEquals(userService.passwordVerify(user, wrongPassword), false); }
@Test public void shouldShowAllUsers() { userService.getAll(); verify(userMapper).findAllUsers(); }
@Test public void shouldReturnUserWhenGetUserId() { Long userId = 1L; userService.get(userId); verify(userMapper).findByUserId(userId); }
@Test public void shouldRuturnUserRoleWhenInvoked() { userService.getUserRoleById(user.getId()); verify(userRoleMapper).get(user.getId()); }
@Test public void shouldInsertUserWhenCreateNew() { userService.save(user); verify(userMapper).insert(user); }
@Test public void subscribeUser() { service.subscribeUser(new User()); verify(userRepository, times(1)).save(Matchers.any(User.class)); }
@Test public void shouldUpdateUserInfoWhenUpdate() { userService.update(user); verify(userMapper).update(user); }
@Test public void shouldUpdateUserRoleWhenInvokeUpdateUserRole() { userService.updateUserRole(userRole); verify(userRoleMapper).update(userRole); }
private void addUsers() { UserServiceImpl service = new UserServiceImpl(); service.addUser("chgri", "Chris", "Grivas", Role.ADMIN); }