@Test
public void testUserHandlerMethodArgument() throws Exception {
// create a tmp test user "TEST2_USER" for this test
User user = new User();
user.setUserId("TEST2_USER");
user.setUserName("TEST2_USER");
user.setEmail("TEST2_USER@nhn.com");
user.setPassword("123");
user.setRole(Role.USER);
user = userRepository.save(user);
User testUser = getTestUser();
testUser.setFollowers(Lists.newArrayList(user));
userRepository.save(testUser);
resolver = new UserHandlerMethodArgumentResolver() {
@Override
Cookie[] getCookies(NativeWebRequest webRequest) {
return new Cookie[] { new Cookie("switchUser", switchUser) };
}
};
resolver.setUserService(userService);
MethodParameter parameter = mock(MethodParameter.class);
final Class<?> class1 = User.class;
when(parameter.getParameterType()).thenAnswer(new Answer<Class<?>>() {
@Override
public Class<?> answer(InvocationOnMock invocation) throws Throwable {
return class1;
}
});
assertThat(resolver.supportsParameter(parameter), is(true));
// test1 scenario: general user can not check other user's script
// has parameter "ownerId", and current user is general, resolved user is "TEST_USER"
ServletWebRequest webRequest1 = mock(ServletWebRequest.class);
when(webRequest1.getParameter("ownerId")).thenReturn("TEST2_USER");
resolver.setUserContext(mockUserContext);
Object resolveArgument1 = resolver.resolveArgument(parameter, null, webRequest1, null);
assertThat(((User) resolveArgument1).getUserId(), is(getTestUser().getUserId()));
// test2 scenario: admin can check other user's script
// has parameter "ownerId", and current user is Admin, resolved user is "TEST2_USER"
ServletWebRequest webRequest2 = mock(ServletWebRequest.class);
when(webRequest2.getParameter("ownerId")).thenReturn("TEST2_USER");
User adminUser = new User("tmpAdminId", "tmpAdminId", "tmpAdminPwd", "admin@nhn.com", Role.ADMIN);
MockUserContext adminUserContext = mock(MockUserContext.class);
when(adminUserContext.getCurrentUser()).thenReturn(adminUser);
resolver.setUserContext(adminUserContext);
Object resolveArgument2 = resolver.resolveArgument(parameter, null, webRequest2, null);
assertThat(((User) resolveArgument2).getUserId(), is("TEST2_USER"));
// test3 scenario: general user switch to use other's permission
// has parameter "switchUser", resolved user id is "TEST2_USER"
ServletWebRequest webRequest3 = mock(ServletWebRequest.class);
switchUser = "TEST2_USER";
resolver.setUserContext(mockUserContext);
User resolveArgument3 = cast(resolver.resolveArgument(parameter, null, webRequest3, null));
assertThat(((User) resolveArgument3).getUserId(), is("TEST_USER"));
// current user's owner is "TEST2_USER"
// assertThat(resolveArgument3.getOwnerUser().getUserId(), is("TEST2_USER"));
// test4 scenario: general user switch back to its own user permission