Change User Within JUnit Test Case in Google AppEngine
Google AppEngine (Java) provides ability to mock UserService in JUnit test cases with the help of LocalUserServiceTestConfig. However, switching user within a test case is not so simple.
Switching user within a test case allows simulation of multi-user scenarios such as:
Bob creates BobMessage.
Cat logs in and is able to see BobMessage.
Dan logs in and is not able to see BobMessage.
Solution
Create a loginAs(String, Closure) method in Groovy to switch the injected UserService within Spring MVC controller object.
@BeforepublicvoidsetUp(){super.setUp()newLocalServiceTestHelper(newLocalUserServiceTestConfig()).setEnvAttributes(['com.google.appengine.api.users.UserService.user_id_key':'bob-101']).setEnvEmail('bob@bob.com').setEnvAuthDomain('bob.com').setEnvIsLoggedIn(true).setUp()}voidloginAs(Stringusername,Closureclosure){UserServicemockUserService=mock(UserService)when(mockUserService.currentUser).thenReturn(newUser("${username}@test",'test',"${username}-id"))UserServicebackupUserService=controller.userServicecontroller.userService=mockUserServiceclosure.call()controller.userService=backupUserService}@Testvoid'multiusertestcase'(){// default user is bob@bob.com as configured in @BeforeassertEquals('bob@bob.com',controller.userService.currentUser.email)// login as 'ace' and execute assertion in closureloginAs('ace',{assertEquals('ace@test',controller.userService.currentUser.email)})// login as 'cat' and execute assertion in closureloginAs('cat',{assertEquals('cat@test',controller.userService.currentUser.email)})// post loginAs method, user reverts to value set in @BeforeassertEquals('bob@bob.com',controller.userService.currentUser.email)}
Requirements
Google App Engine (Java)
SpringMVC (@Controller with injected UserService)
Groovy – while this example was coded in Groovy, it is not really a requirement. You can always do similar stuff in Java.