@Before public void setup() { session = mock(SqlSession.class); userMapper = mock(UserMapper.class); userRoleMapper = mock(UserRoleMapper.class); sessionFactory = mock(SqlSessionFactory.class); when(sessionFactory.openSession()).thenReturn(session); when(session.getMapper(UserMapper.class)).thenReturn(userMapper); when(session.getMapper(UserRoleMapper.class)).thenReturn(userRoleMapper); userService = new UserServiceImpl(sessionFactory); user = new User(); user.setUserName("user"); user.setPasswordHash("password"); user.setId(1L); userRole = new UserRole(); userRole.setUserId(1L); userRole.setRoleName("ROLE_REGULAR"); }
@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 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 public boolean matches(Object userroleToMatch) { return ((UserRole) userroleToMatch).getUserId().equals(userRole.getUserId()) && ((UserRole) userroleToMatch).getRoleName().equals(userRole.getRoleName()); }