How to test a DAO with JPA implementation ?

Posted by smallufo on Stack Overflow See other posts from Stack Overflow or by smallufo
Published on 2010-03-21T13:44:50Z Indexed on 2010/03/21 13:51 UTC
Read the original article Hit count: 432

Filed under:
|
|
|
|

Hi I came from the Spring camp , I don't want to use Spring , and am migrating to JavaEE6 , But I have problem testing DAO + JPA , here is my simplified sample :

public interface PersonDao
{
  public Person get(long id);
}

This is a very basic DAO , because I came from Spring , I believe DAO still have it value , so I decided to add a DAO layer .

public class PersonDaoImpl implements PersonDao , Serializable
{
  @PersistenceContext(unitName = "test", type = PersistenceContextType.EXTENDED)
  EntityManager entityManager ;

  public PersonDaoImpl()
  {
  }

  @Override
  public Person get(long id)
  {
    return entityManager .find(Person.class , id);
  }
}

This is a JPA-implemented DAO , I hope the EE container or the test container able to inject the EntityManager.

public class PersonDaoImplTest extends TestCase
{
  @Inject 
  protected PersonDao personDao;

  @Override
  protected void setUp() throws Exception
  {
    //personDao = new PersonDaoImpl();
  }

  public void testGet()
  {
    System.out.println("personDao = " + personDao); // NULL !
    Person p = personDao.get(1L);
    System.out.println("p = " + p);
  }
}

This is my test file .

OK , here comes the problem : Because JUnit doesn't understand @javax.inject.Inject , the PersonDao will not be able to injected , the test will fail.

How do I find a test framework that able to inject the EntityManager to the PersonDaoImpl , and @Inject the PersonDaoImpl to the PersonDao of TestCase ?

I tried unitils.org , but cannot find a sample like this , it just directly inject the EntityManagerFactory to the TestCast , not what I want ...

© Stack Overflow or respective owner

Related posts about jpa

Related posts about dao