使用 OpenEJB 进行 EJB 存储库测试 - 如何回滚更改
我尝试使用 OpenEJB 测试基于 EJB 的存储库。每次运行新的单元测试时,我都希望我的数据库处于“初始”状态。测试结束后,所有更改都应该回滚(无论测试是否成功)。如何以简单的方式完成它?我尝试使用 UserTransaction - 在测试开始时启动它并在完成时回滚更改(如下所示)。我不知道为什么,但是使用此代码,数据库中的所有更改(在单元测试期间完成)都会在执行行回滚更改后保留。 正如我所写,我想以最简单的方式完成它,而不需要任何外部数据库模式等。
预先感谢您的任何提示!
皮奥特尔
public class MyRepositoryTest {
private Context initialContext;
private UserTransaction tx;
private MyRepository repository; //class under the test
@Before
public void setUp() throws Exception {
this.initialContext = OpenEjbContextFactory.getInitialContext();
this.repository = (MyRepository) initialContext.lookup(
"MyRepositoryLocal");
TransactionManager tm = (TransactionManager) initialContext.lookup(
"java:comp/TransactionManager");
tx = new CoreUserTransaction(tm);
tx.begin();
}
@After
public void tearDown() throws Exception {
tx.rollback();
this.initialContext = null;
}
@Test
public void test() throws Exception {
// do some test stuff
}
}
I try to test my EJB-based repositories using OpenEJB. Every time new unit test is runned I'd like to have my DB in an "initial" state. After the test, all changes should be rolled back (no matter if test succeeded or not). How to accomplish it in a simple way? I tried using UserTransaction - beginning it when test is starting and rolling back changes when finishing (as you can see below). I don't know why, but with this code all changes in DB (which were done during unit test) are left after line rolling changes back has been executed.
As I wrote, I'd like to accomplish it in the simplest way, without any external DB schema and so on.
Thanks in advance for any hints!
Piotr
public class MyRepositoryTest {
private Context initialContext;
private UserTransaction tx;
private MyRepository repository; //class under the test
@Before
public void setUp() throws Exception {
this.initialContext = OpenEjbContextFactory.getInitialContext();
this.repository = (MyRepository) initialContext.lookup(
"MyRepositoryLocal");
TransactionManager tm = (TransactionManager) initialContext.lookup(
"java:comp/TransactionManager");
tx = new CoreUserTransaction(tm);
tx.begin();
}
@After
public void tearDown() throws Exception {
tx.rollback();
this.initialContext = null;
}
@Test
public void test() throws Exception {
// do some test stuff
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
3.1.4 的示例 zip 中有一个名为“transaction-rollback”的示例。
检查一下,因为它有多种方法可以在单元测试中回滚。其中一项技术包括为每次测试获取新的内存数据库的技巧。
There's an example called 'transaction-rollback' in the examples zip for 3.1.4.
Check that out as it has several ways to rollback in a unit test. One of the techniques includes a trick to get a new in memory database for each test.