dadrus / jpa-unit

JUnit extension to test javax.persistence entities
Apache License 2.0
29 stars 9 forks source link

Accessing global EntityManager instance in JUnit5 @Nested classes #46

Open holyhoehle opened 5 years ago

holyhoehle commented 5 years ago

When I try to access a global EntityManager instance from @Nested classes I get the following exception: java.lang.IllegalArgumentException: JPA test must have either EntityManagerFactory or EntityManager field annotated with @PersistenceUnit, respectively @PersistenceContext

My class looks like this:

@ExtendWith(JpaUnit.class)
class NestedTest {

    @PersistenceContext(unitName = "my-test-unit")
    private EntityManager entityManager;

    @Nested
    @DisplayName("Given an empty test table")
    class GivenAnEmptyTestTable {

        @Test
        @DisplayName("Then the size sould be zero")
        void thenTheSizeShouldBeZero() {
            List<Test> list = entityManager
                    .createQuery("select t from Test t", Test.class)
                    .getResultList();
            assertEquals(list.size(), 0);
        }

        @Nested
        @DisplayName("When a row is inserted")
        class WhenARowIsInserted {

            @BeforeEach
            @Transactional(TransactionMode.COMMIT)
            void setUp() {
                Test t = new Test(1, 2, 3);
                entityManager.persist(t);
            }

            @Test
            @DisplayName("Then the size should be one")
            void thenTheSizeShouldBeOne() {
                List<Test> list = entityManager
                        .createQuery("select t from Test t", Test.class)
                        .getResultList();
                assertEquals(list.size(), 0);
            }
        }
    }
}

Is it somehow possible to keep the entityManager instance in the nested tests?

dadrus commented 5 years ago

Hi, This has not been implemented yet. Sorry. If you like you can submit a pull request. I'll be glad to see it.