I am using reflection to check if a private variable is set to null after the logout function. This is needed because the getUser function will always attempt to set and return an user if no user is set. Am I doing something wrong or can I do something better?
This is the bean that has the logout and getUser function:
@ManagedBean(name = "authBean")
@SessionScoped
public class AuthorizationBean implements Serializable{
//Data access object for the users
@Inject
UserDao userDao;
private User user; // The JPA entity.
public User getUser() {
if (user == null) {
user = (User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user");
if (user == null) {
Principal principal = FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
if (principal != null) {
user = userDao.findByEmail(principal.getName()); // Find User by j_username.
}
}
}
return user;
}
/**
* Function that handles the logout
* @return Redirect string that points to the login page
*/
public String doLogout() {
// invalidate the session, so that the session is removed
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
user = null;
// return redirect to login page
return "/login.xhtml?faces-redirect=true";
}
}
This is the test class, with the reflection:
@RunWith(PowerMockRunner.class)
@PrepareForTest(FacesContext.class)
public class AuthorizationBeanTest {
private AuthorizationBean authorizationBean;
@Mock
User user;
@Mock
FacesContext facesContext;
@Mock
ExternalContext externalContext;
@Before
public void setUp() {
authorizationBean = new AuthorizationBean();
Map<String,Object> sessionMap = new HashMap<>();
sessionMap.put("user", user);
//Mocking the static function getCurrentInstance from FacesContext,
//so a mocked user can be returned for the test
PowerMockito.mockStatic(FacesContext.class);
PowerMockito.when(FacesContext.getCurrentInstance()).thenReturn(facesContext);
when(facesContext.getExternalContext()).thenReturn(externalContext);
when(externalContext.getSessionMap()).thenReturn(sessionMap);
}
@Test
public void doLogoutTest() throws NoSuchFieldException, IllegalAccessException {
assertNotNull(authorizationBean.getUser());
assertEquals("/login.xhtml?faces-redirect=true", authorizationBean.doLogout());
//Check through reflection if the private field user is now null
Field userField = authorizationBean.getClass().getDeclaredField("user");
userField.setAccessible(true);
User testUser = (User) userField.get(authorizationBean);
assertNull(testUser);
}
}