This post is for mocking FacesContext on junit
I don't want to create a subclass like FacesContextMock
Described as a memorandum how to use PowerMock and do it in the @ Test method
Use the following libraries and versions
UserAuth Session management of user information
UserAuth.java
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
/**
*User credentials
*/
@ManagedBean
@SessionScoped
public class UserAuth implements Serializable {
/**User ID*/
private String userId;
/**Login status*/
private boolean logined;
/**
*Logout process
*
* @return login screen URL
*/
public String logout() {
//Discard session information
FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
//Transit to login screen by redirect
return "/login.xhtml?faces-redirect=true";
}
// ... Setter and Getter
}
** UserAuth test ** Test the logout process
UserAuth.java
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
/**
*UserAuth test class
*/
@RunWith(PowerMockRunner.class)
public class UserAuthTest {
/**User credentials*/
private UserAuth userAuth;
/**
*Instantiate user credentials class
*/
@Before
public void bofore() {
userAuth = new UserAuth();
}
/**
*Test logout process<br>
*The URL of the logout destination is the login screen.
*/
@Test
@PrepareForTest(FacesContext.class)
public void testLogout() {
//mock
PowerMockito.mockStatic(FacesContext.class);
FacesContext context = PowerMockito.mock(FacesContext.class);
ExternalContext ext = PowerMockito.mock(ExternalContext.class);
//method setting
PowerMockito.when(FacesContext.getCurrentInstance()).thenReturn(context);
PowerMockito.when(context.getExternalContext()).thenReturn(ext);
//Check the URL of the logout destination.
assertThat(userAuth.logout(), containsString("login.xhtml"));
}
}
To use PowerMockito
@ RunWith (PowerMockRunner.class) in class annotation
Add @PrepareForTest (FacesContext.class) to method annotation
@PrepareForTest (FacesContext.class) may be a class annotation.FacesContext.getCurrentInstance () is a static method, so mock it with PowerMockito.mockStatic
All subsequent instances called will be mocked with mock
mock, you can mock with Mockito.mock.After that, when the test is executed, mock is called and processing is performed.
Recommended Posts