1

I am beginner with JAX-RS webservice and its testcase.

My TestController class is as follows:

public class LotTypeMangementServiceTest {

private final String LOT_NAME = "lotName";

@Inject
private LotTypeManagementService lotTypeService;

@Test
private LotType testCreate() {
    LotType newLotType = new LotType();
    newLotType.setName(LOT_NAME);
    
    //save
    lotTypeService.createOrUpdate(newLotType);
    
    Assert.assertNotNull(newLotType.getId());
    
    return newLotType;
  }
}

My LotTypeManagementService as follows:

@Stateless
public class LotTypeManagementService {
        
    @PersistenceContext(unitName="primary")
    private EntityManager em;
    
    public void createOrUpdate(LotType lotType) {
        if (lotType.getId() == null) { // Save New Label Type
            em.persist(lotType);
        } else {    // Update Label Type
            em.merge(lotType);
        }
    }
}

Now as you can see, LotTypeManagementService has EntityManager dependency.

In testclass, I've injected LotTypeManagementService. However, its dependency is not getting injected and hence I em object is NULL.

My persistence.xml file is as below:

<persistence version="2.0"
   xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
        http://java.sun.com/xml/ns/persistence
        http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
   <persistence-unit name="primary">
   
   <jta-data-source>java:jboss/datasources/lottype</jta-data-source>
  
      <properties>
         <property name="hibernate.hbm2ddl.auto" value="update" />
         <property name="hibernate.show_sql" value="true" />
      </properties> 
   </persistence-unit>
</persistence>

My RestController is as below:

@RequestScoped
public class LotTypeResourceRESTService {

    @Inject
    private LotTypeManagementService lotTypeService;
}

I am using wildfly-9.0.1 server, java8, JAX-RS webservice, hibernate, jpa-2.1 and jUnit.

I found some solution on Stack Overflow like

  1. Use @Inject or @Ejb
  2. some change on persistance.xml <provider>org.hibernate.ejb.HibernatePersistence</provider>
  3. em = (EntityManager) new nitialContext().lookup("java:/primary");
  4. Like create dynamically container.

How can I do this correctly?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65

0 Answers0