How to test a Controller and Model in a JSF Project with jUnit? - jsf

i don't know exactly how to write tests for these following Classes especially for the Controller and Model. Is it to possible to test with jUnit ?
I heard from Selenium but first i would test with jUnit. Thanks for ur help and best regards.
Controller.class:
import factory.InfoMessageFactory;
import entity.Product;
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import model.ProductModel;
import project.Konstanten;
#Named(value = "ProductController")
#SessionScoped
public class ProductController implements Serializable {
private Product product;
#Inject
private ProductModel model;
#PostConstruct
public void init() {
this.product = new Product();
}
public String addProduct() {
this.model.newProduct(this.product);
}
public Product getProduct() {
return product;
}
public void setProdukt(Product product) {
this.product = product;
}
public List<Product> getProducts() {
return this.model.getProducts();
}
}
Model.class
package model;
import ejb.DB;
import entity.Product;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
#Dependent
public class ProductModel implements Serializable{
#Inject
private DB db;
public boolean addProduct(Product p){
try{
db.persist(p);
}catch(Exception e){
System.out.println("Blablabla");
return false;
}
return true;
}
}
And DB.class
#Stateless
public class DB {
#Inject
#RealClass
private EntityManager em;
public void persist(Object object) {
em.persist(object);
}

In the ProductController, there is really not much to test.. unless there is more logic that you did not post.
For testing the ProductModel, or any service-like class having the DB dependency i would suggest adding a project dependency to one of the mocking frameworks (i suggest Mockito as it is the most mature of them all).
For the addProducts method you could end up with following tests:
import static org.mockito.Mockito.*;
import org.junit.Test;
import org.mockito.MockitoAnnotations;
public class ProductModelTest{
#Mock
private DB dbMock;
#InjectMocks
private ProdcutModel = new ProductModel();
#Before
public void init(){
MockitoAnnotations.iniMocks(this);
}
#Test
public void shouldReturnTrue_whenEntityPersisted(){
doNothing().when(dbMock).persist(any(Product.class));
boolean result = productModel.addProduct(new Product());
assertTrue(result);
}
#Test
public void shouldReturnFalse_whenEntityPersisted(){
doThrow(RuntimeException.class).when(dbMock).persist(any(Product.class));
boolean result = productModel.addProduct(new Product());
assertFalse(result);
}
}
Regarding the DB-like repository classes.. i normally do not unit-test them. IF so i run integration tests on them.

Related

Quarkus Panache Mockito fails

I struggle with mocking a Panache repository.
Here is the Entity:
import javax.persistence.*;
#Entity
public class Thing {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Simple repository:
import io.quarkus.hibernate.orm.panache.PanacheRepository;
import javax.enterprise.context.ApplicationScoped;
#ApplicationScoped
public class ThingRepository implements PanacheRepository<Thing> {
}
This is the resource:
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.List;
#Path("/things")
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
public class ThingResource {
#Inject
ThingRepository thingRepository;
#GET
public List<Thing> list() {
return thingRepository.listAll();
}
}
and a simple test where I try to mock the repository:
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectMock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertNotNull;
#QuarkusTest
class ThingResourceTest {
private Thing thing;
#Inject ThingResource thingResource;
#InjectMock ThingRepository thingRepository;
#BeforeEach
void setUp() {
Thing thing = new Thing();
thing.setId(1L);
}
#Test
void getAll() {
List<Thing> things = new ArrayList<Thing>();
things.add(thing);
Mockito.when(thingRepository.listAll()).thenReturn(things);
List<Thing> response = thingResource.list();
assertNotNull(response);
assertNotNull(response.get(0));
}
}
The test fails because the response list is <null>.
The debugger tells me the thingRepository is actually mocked. But for some reason Mockito.when().thenReturns() does not return the list I set up.
What am I missing?
Thank you for any help.
I had the thing double declared. One time as class variable, and again in setUp(). Bummer. I apologize for the noise.

How to Inject FacesContext in Arquillian

Is it possible to inject FacesContext in Arquillian test? Or better approach is to mock it? I couldn't find any example from the last years on the web. FacesContext is null.
#Category(Arquillian.class)
#RunWith(Arquillian.class)
public class ControllerIT extends ArquillianDeployementsIT {
#Inject
private Controller controller;
#Test
public void shouldInitialize() {
controller.getStatistics();
}
#ManagedBean
#ViewScoped
public class Controller {
public void getStatistcs(
FacesContext context = FacesContext.getCurrentInstance();
}
}
Thanks and regards
Finally I solved the problem like this, maybe it helps someone.
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.servlet.http.HttpServletRequest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class ContextMocker extends FacesContext {
private static final Release RELEASE = new Release();
private ContextMocker() {
}
public static FacesContext mockServletRequest() {
FacesContext context = mock(FacesContext.class);
setCurrentInstance(context);
Mockito.doAnswer(RELEASE)
.when(context)
.release();
Map<String, Object> session = new HashMap<>();
ExternalContext ext = mock(ExternalContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(ext.getSessionMap()).thenReturn(session);
when(context.getExternalContext()).thenReturn(ext);
when(ext.getRequest()).thenReturn(request);
when(ext.isUserInRole(anyString())).thenReturn(true);
return context;
}
private static class Release implements Answer<Void> {
#Override
public Void answer(InvocationOnMock invocation) throws Throwable {
setCurrentInstance(null);
return null;
}
}
}
and in the test:
#Category(Arquillian.class)
#RunWith(Arquillian.class)
public class LoginControllerIT extends ArquillianWebIT {
#Inject
private LoginController loginController;
private FacesContext facesContext;
#Before
public void init() {
facesContext = ContextMocker.mockServletRequest();
}
#After
public void release() {
facesContext.release();
}
#Test...

JSF Interceptor doesn't fire

Why my interceptor doesn't work?
MyLog.java
#Inherited
#InterceptorBinding
#Retention(RUNTIME)
#Target({METHOD, TYPE})
public #interface MyLog {
}
MyLogger.java
#Interceptor
#MyLog
#Priority(Interceptor.Priority.APPLICATION)
public class MyLogger {
#AroundInvoke
public Object log(InvocationContext context) throws Exception{
System.out.println("begin " + context.getMethod().getName());
Object obj = context.proceed();
System.out.println("end " + context.getMethod().getName());
return obj;
}
}
PerguntaController.java
import interceptor.MyLog;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
#Named("PerguntaController")
#SessionScoped
public class PerguntaController implements Serializable {
#EJB
private PerguntaFacade ejbFacade;
#MyLog
public List<> getAll() {
return ejbFacade.getAll();
}
#MyLog
public void update(Pergunta pergunta) {
ejbFacade.update(pergunta);
}
}
PerguntaFacade.java
import interceptor.MyLog;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PerguntaFacade {
#PersistenceContext(unitName = "WebApplicationPU")
private EntityManager em;
#MyLog
public List<Pergunta> getAll() {
return em.createQuery("SELECT p FROM Pergunta p", Pergunta.class).getResultList();
}
#MyLog
public void update(Pergunta pergunta) {
//do something
}
}
When use getAll and update (from PerguntaController) in jsf page doesn't fire the interceptor neither getAll and update on PerguntaFacade. What im doing wrong?
Solved.
On beans.xml with bean-discovery-mode="annotated" doesn't work.
Then change to bean-discovery-mode="all" and works fine.

visibility of property set in #PostConstruct in ManagedBean

i am tryiing to get property value in my #RequestScoped Bean which is set in #PostConstruct. I have editUser page witch get userId from other page, and i am getting user from database in #PostConstruct, but when i try to edit that user in same page, user object is null, in method editUser.
Is there a way to get that object, which is set in PostConstruct?
Here is my EditUserBean:
package ba.nedim.colaborationtoolapp.model;
import ba.nedim.colaborationtoolapp.dto.UserDTO;
import ba.nedim.colaborationtoolapp.services.RegisterService;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import org.primefaces.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
#ManagedBean
#RequestScoped
public class EditUserBean implements Serializable{
#EJB
private RegisterService userService;
private final Logger log = LoggerFactory.getLogger(EditUserBean.class);
private int idUser;
#ManagedProperty("#{param.id}")
private int actionId;
public int getActionId() {
return actionId;
}
public void setActionId(int actionId) {
this.actionId = actionId;
}
private UserDTO user = new UserDTO();
public UserDTO getUser() {
return user;
}
public void setUser(UserDTO user) {
this.user = user;
}
#PostConstruct
private void initialize(){
if(actionId!=0){
setUser(userService.getUserByID(actionId));
}
}
public void editUser(){
UserDTO user = getUser();
log.info("UserID:" + user.getIdusers());
}
private String gotoUserPage(){
return "users";
}
}
After the page has been fully rendered, the #RequestScoped bean is destroyed along with all its instance variables (including the user). I presume this is the point at which you then attempt to execute editUser() which results in an NPE.
Use a #ViewScoped bean instead, to ensure your instance variables survive a postback to the same view

JSF - Getting NullPointerException in constructor when accessing getFacade()

this code produces NullPointerException. I don't know why. When I put the code from constructor to some other void with #PostConstruct - it works. I tried to initiate klientFacade - but it's not working, either. The class KlientFacade is #Stateless.
package view;
import entity.Klient;
import facade.KlientFacade;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import static util.Messages.addFlashMessage;
#ManagedBean
#ViewScoped
public class ManageClient implements Serializable {
#EJB
private KlientFacade klientFacade;
private List<Klient> clientList;
public List<Klient> returnClientList(){
return getKlientFacade().findAll();
}
public ManageClient() {
clientList = new ArrayList<>();
clientList = returnClientList();
}
public String removeClient(Klient klient){
addFlashMessage("Klient ["+klient.getLogin()+"] został usunięty.");
getKlientFacade().remove(klient);
return "manage";
}
public List<Klient> getClientList() {
return clientList;
}
public void setClientList(List<Klient> clientList) {
this.clientList = clientList;
}
public KlientFacade getKlientFacade() {
return klientFacade;
}
public void setKlientFacade(KlientFacade klientFacade) {
this.klientFacade = klientFacade;
}
}
Well its because injected objects are not instantiated before the constructor call. Thats why you are not getting NPE with #PostConstruct annotation. If you still need to access injected fields in constructor, try http://openejb.apache.org/constructor-injection.html.

Resources