I'm trying to work out the best way to unit test a javax.faces.view.ViewScoped
bean, for example
@Named
@ViewScoped
public class UserController implements Serializable
{
@Inject
private UserService userService;
private List<User> users;
private User user;
/**
* Init method used to initialise users list
*/
@PostConstruct
public void init()
{
users = userService.listAll();
}
/**
* Delete the specified user
*
* @param user User to be deleted
*/
public void delete(User user)
{
userService.deleteUser(user);
}
/**
* Add a user with the specified name
*
* @param usr Name of the user to be added
*/
public void add(String usr)
{
user = new User();
user.setName(usr);
userService.addUser(user);
}
public List<User> getUsers()
{
return users;
}
public User getUser()
{
return user;
}
}
I believe I shouldn't need to test getUsers()
and getUser()
, but I should be testing init()
, add()
and delete()
.
After some googling around the topic I found the following answer http://ift.tt/1FyfegG
Which so far has given me this test code
@RunWith(PowerMockRunner.class)
@PrepareForTest(
{
FacesContext.class
})
public class UserControllerTest
{
private final Map<String, Object> viewMap = Maps.newHashMap();
@Mock
private UserService service;
@Mock
private FacesContext facesContext;
@Mock
private UIViewRoot uiViewRoot;
@Before
public void setUp()
{
Mockito.doReturn(this.uiViewRoot).when(this.facesContext).getViewRoot();
Mockito.doReturn(this.viewMap).when(this.uiViewRoot).getViewMap();
PowerMockito.mockStatic(FacesContext.class);
Mockito.when(FacesContext.getCurrentInstance()).thenReturn(this.facesContext);
}
@Test
public void testUsersListInitialised()
{
FacesContext.getCurrentInstance().getViewRoot().getViewMap();
}
}
I'm getting a little confused however by the view map and the UIViewRoot
, I believe with this code the map will be empty
So going by this answer http://ift.tt/1LisFsj
I won't simply be able to say
Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
UserController userController = (UserController) viewMap.get("userController");
What am I missing? Am I going about this the right way?
Aucun commentaire:
Enregistrer un commentaire