使用不同的持久性单元进行测试

发布于 2024-11-24 09:16:57 字数 698 浏览 0 评论 0原文

我已经为几个无状态会话 bean 创建了单元测试。当我在嵌入式 GlassFish 容器中运行这些测试时,将使用我的项目的默认持久性单元,这是用于开发目的的本地 MySQL 数据库。然而,在运行单元测试时,我希望使用嵌入式 Derby 数据库,以便任何单元测试都不会用模拟数据弄乱数据库。

在 OpenEJB 中,可以通过创建哈希映射并放置一些属性来覆盖 persistence.xml,如下所示:

Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

p.put("movie-unit.hibernate.hbm2ddl.auto", "update");
p.put("movie-unit.hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

context = new InitialContext(p);

Sun 的实现是否可以在不同的数据库上运行单元测试?

编辑:我正在使用 Ant 来构建项目。我想可以在运行测试时复制测试 persistence.xml,并复制常规的 persistence.xml 进行部署,但这看起来很笨拙。切换到 Maven 是否明智?

I have several stateless session beans I have created unit tests for. When I run these tests in the embedded GlassFish container, the default persistence unit for my project is used, which is a local MySQL database for development purposes. When running the unit tests however, I wish to use the embedded Derby database so that any unit testing does not clutter the database with mock data.

In OpenEJB, it is possible to override persistence.xml by creating a hash map and putting some properties, like so:

Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY,"org.apache.openejb.client.LocalInitialContextFactory");

p.put("movie-unit.hibernate.hbm2ddl.auto", "update");
p.put("movie-unit.hibernate.dialect", "org.hibernate.dialect.HSQLDialect");

context = new InitialContext(p);

Is the same or something similar possible with Sun's implementation to run unit tests on a different database?

Edit: I am using Ant to build the project. I guess it would be possible to copy the testing persistence.xml when running a test, and copy the regular persistence.xml for deployments but this seems clunky. Would switching to Maven be advisable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏夜暖风 2024-12-01 09:16:58

我不知道你用的是什么类型的构建工具。

在 Maven 中,运行时资源和测试资源是分开的:

project 
 |- src/main/resources
 |- src/test/resources

src/test/resources 中的资源不包含在最终工件中,仅在测试期间由单元测试插件 (Surefire) 使用构建阶段。

无论使用什么工具,我建议您对资源进行这种分离,以便能够实现您正在寻找的结果。

I don't know what sort of build tool you're using.

In Maven you have a separation between runtime and test resources:

project 
 |- src/main/resources
 |- src/test/resources

The ones in src/test/resources aren't included in your final artifact and are only used by the unit testing plugin (Surefire) during the testing phase of the build.

Whatever the tool, I suggest you have this sort of separation between the resources in order to be able to achieve the result you're looking for.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文