我從春天陣營來了,我不想使用Spring,並正在遷移到JavaEE6, 但我有問題的測試DAO + JPA,這裏是我的簡單示例:如何使用JPA實現測試DAO?
public interface PersonDao
{
public Person get(long id);
}
這是一個非常基本的DAO,因爲我來自Spring,我相信DAO仍然有其價值,所以我決定添加一個DAO層。
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);
}
}
這是一個JPA實現的DAO,我希望EE容器或測試容器能夠注入EntityManager(就像Spring一樣)。
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);
}
}
這是我的測試文件。
好的,問題來了: 因爲JUnit不理解@ javax.inject.Inject,所以PersonDao將無法注入,測試將失敗。
如何找到一個測試框架,能夠EntityManager的注入到PersonDaoImpl和@Inject的PersonDaoImpl到的TestCase的PersonDao的?
我試過unitils.org,但無法找到這樣的樣品,它只是直接注入的EntityManagerFactory到TestCast,不是我想要的......
至於JPA是否殺死了DAO,這取決於。在某些情況下,您希望重構JPA代碼,以便您可以在其他位置重用該代碼。那麼什麼是比DAO更好的地方? – BalusC 2010-03-21 18:03:15
@BalusC我不同意「系統使用DAO」,我同意「這取決於」,但......但並不完全是因爲你給的原因(我不是說你錯了,但我希望看到你的例子的一個具體的例子,我在想象它時遇到了一些困難)。 – 2010-03-21 18:15:19
還沒有,我還沒有在真實世界的項目中使用過JPA,只是嘲笑它而已。但我可以想象,無論何時您需要重複相同的一組JPA代碼行,如果您的代碼行數超過3〜5行,您都希望將其重構,而且我還無法想象「正確」放置這些行。是DAO類嗎? – BalusC 2010-03-21 18:21:49