问题是“自己动手”的API,并没有利用嵌入式EJB容器。您可以非常轻松地在测试用例中管理容器。Persistence.createEntityManagerFactory("abc")
EntityManager
就像相关的jndi/数据源问题一样,我建议您查看示例中的示例.zip。它们都是为了摆脱入门的挣扎而设计的。
下面是示例中的一个片段,演示如何从容器中获取 EntityManager 和其他内容以用于测试。testcase-injection
首先,将空的 ejb-jar.xml 或 application-client.xml添加到测试中,以打开对测试代码的扫描:
- src/test/resources/META-INF/application-client.xml
然后,使用标准 JavaEE 注释来注释测试用例,并将其用于实际注入。@org.apache.openejb.api.LocalClient
@LocalClient
public class MoviesTest extends TestCase {
@EJB
private Movies movies;
@Resource
private UserTransaction userTransaction;
@PersistenceContext
private EntityManager entityManager;
public void setUp() throws Exception {
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
p.put("movieDatabase", "new://Resource?type=DataSource");
p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver");
p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb");
InitialContext initialContext = new InitialContext(p);
// Here's the fun part
initialContext.bind("inject", this);
}
作为我们设置的唯一数据源,OpenEJB 会自动将该数据源分配给您的持久性单元,而无需修改持久性.xml。您甚至可以将 或 留空,OpenEJB 仍然会知道该怎么做。movieDatabase
<jta-data-source>
<non-jta-data-source>
但为了完整起见,下面是此特定应用程序如何定义persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="movie-unit">
<jta-data-source>movieDatabase</jta-data-source>
<non-jta-data-source>movieDatabaseUnmanaged</non-jta-data-source>
<class>org.superbiz.testinjection.Movie</class>
<properties>
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
</properties>
</persistence-unit>
</persistence>
然后是有趣的部分,在测试中一起使用
public void test() throws Exception {
userTransaction.begin();
try {
entityManager.persist(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
entityManager.persist(new Movie("Joel Coen", "Fargo", 1996));
entityManager.persist(new Movie("Joel Coen", "The Big Lebowski", 1998));
List<Movie> list = movies.getMovies();
assertEquals("List.size()", 3, list.size());
for (Movie movie : list) {
movies.deleteMovie(movie);
}
assertEquals("Movies.getMovies()", 0, movies.getMovies().size());
} finally {
userTransaction.commit();
}
}