问题
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