Get current Spring transaction in JUnit and commit it

梦想的初衷 提交于 2021-01-28 21:44:15

问题


is it possible to get current Spring transaction in JUnit?

I want to test JPA in DAO. And DAO do not have transactions. In tests spring create transaction for every method. I want transaction to be commited somewhere in the middle of test. Need it to test DB status. Only solution I found is to create @Rule for every method.


回答1:


You can use TestTransaction in order to manage spring test transactions:

TestTransaction.flagForCommit();
TestTransaction.end();

This will flag the current transaction for commit and end it. After that you can use TestTransaction.start() to start a new transaction.




回答2:


You can :

  • Inject the EntityMananger in your test
  • Call flush() after the invocation of your DAO
  • Use this EntityManager to test the db

It's always better to keep the default behavior of spring on transaction/rollback in order to minimize side-effects between tests



来源:https://stackoverflow.com/questions/35113220/get-current-spring-transaction-in-junit-and-commit-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!