我解決了創建一個Stateless Session Bean
並注入其Entity Manager
來測試類。我張貼萬一有人代碼會需要它:
@Stateless(name = "TestProxy")
@Remote({TestProxyRemote.class})
public class TestProxy implements TestProxyRemote {
@PersistenceContext(unitName = "mph")
private EntityManager em;
@Override
public void persist(Object o) {
em.persist(o);
}
@Override
public void clear() {
em.clear();
}
@Override
public void merge(Object o) {
em.merge(o);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object find(Class classe, String key) {
return em.find(classe, key);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object find(Class classe, long key) {
return em.find(classe, key);
}
@SuppressWarnings("rawtypes")
@Override
public List getEntityList(String query) {
Query q = em.createQuery(query);
return q.getResultList();
}
}
public class MyTest {
@BeforeClass
public static void setUpBeforeClass() throws NamingException {
Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
env.setProperty(Context.PROVIDER_URL, "localhost:1099");
env.setProperty("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
jndiContext = new InitialContext(env);
try {
proxy = (TestProxyRemote) jndiContext.lookup("TestProxy/remote");
} catch (NamingException e) {
e.printStackTrace();
}
}
}
那麼我可以用proxy.find()
得到我所需要的實體,鄰proxy.getEntityList()
執行查詢檢索的實體的所有實例。或者我可以添加其他方法,如果我想。
你如何編寫測試用例?你是否使用像Arquillian這樣的集成框架或像OpenEJB這樣的嵌入式EJB容器? –
@PiotrNowicki我試了兩種(使用mockito作爲框架)。我不知道如何設置它們,我需要導入...無論如何,任何方法都可以。 – Simon
我有一個簡單的例子:http://stackoverflow.com/questions/6469751/testing-an-ejb-with-junit/20635285#20635285。看看我的答案。 –