Announcement Announcement Module
Collapse
No announcement yet.
Spring, JPA, and Unit/Integration Test Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Spring, JPA, and Unit/Integration Test

    I am using JPA and my test classes needs access to an EntityManager so it can execute some SQL during setup/teardown.

    The issue I have is the test methods are using the same transaction as the actual service methods. I have tried to annotated @Transactional(requires_new) specifically only for the setup methods, but that does not work.

    Anyone got a sample on how to inject an entityManager into a test class and have the test class execute certains methods in a transaction context that is different from the transaction context of the service classes?

    Thanks...

  • #2
    Have not tried this but it should work. It should be possible to inject a TestDataInjector object into the Test class. You should setup this class in a separate test-context file.

    However, this does not "Feel good" to me, your data will be persisted to the database and unless you are using an in-memory database you have to manually remove it. Why not setup in the same transaction?

    Code:
    class TestDataInjector {
    
    @PersistenceContext
    private EntityManager entityManager;
    
    public void inject() {// do stuff}
    }
    Code:
    class MyTestClass extends AbstractJpaTests {
    
    public void setTestDataInjector(TestDataInjector injector) {}
    
    public void onSetUpInTransaction() {
        setDefaultRollback(false);
        endTranscation();
       startNewTransaction();
       injector.inject();
      endTransaction();
      setDefaultRollback(false);
    }
    
    }

    Comment

    Working...
    X