简体   繁体   中英

SpringJUnit4ClassRunner - static access to EntityManager(Factory)

I'm using JUnit4 with SpringJUnit4ClassRunner to write some test classes and I need to access the application persistence context inside a static method, a method with the @BeforeClass annotation. My actual code is seen below:

@ContextConfiguration(locations = {
    "classpath:category-datasource-config.xml"
    , "classpath:category-persistence-context.xml"
    , "classpath:spring-data-config-test.xml"
})
public class CategoryTopographicalViewIntegrationTest extends BaseTest {

    @Autowired
    private CategoryService categoryService;

    @PersistenceContext
    private EntityManager em;

    @BeforeClass
    public static void setupDatabase() {
        // I need the EntityManager HERE!

        suppressCategories(Tenant.MCOM, new Long[] { 16906L, 10066L, 72795L, 72797L, 72799L, 72736L }, ContextType.DESKTOP);
        suppressCategories(Tenant.BCOM, new Long[] { 1001940L }, ContextType.DESKTOP);

        if (!contextualCategoryExists(9326L, ContextType.DESKTOP)) {
            ContextualCategoryEntity cce = new ContextualCategoryEntity();
            cce.setCategory(em.find(CategoryEntity.class, 9326L));
            cce.setCategoryName("Immutable Collections");
            cce.setContextType(ContextType.DESKTOP);
            cce.setSequence(30);
            cce.setSuppressed(Boolean.FALSE);

            em.persist(cce);
        }
        em.flush();
    }
    ...
}

How can I accomplish that? I do not have a persistence.xml file, the persistence context bean is configured inside a Spring XML config file:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="packagesToScan" value="com.macys.stars.category.domain"/>
    <property name="dataSource" ref="dataSource"/>
    <property name="jpaVendorAdapter" ref="hibernateVendorAdapter"/>
</bean>

Thanks in advance!

With JUnit 4 it is not possible to access Spring beans in a static @BeforeClass method. Beans from the ApplicationContext can only be injected once the test class has been instantiated.

However, you can implement a custom TestExecutionListener (eg, by extending AbstractTestExecutionListener and overriding the beforeTestClass(...) method) and register it via @TestExecutionListeners . Your listener can then do the work of your @BeforeClass method by explicitly retrieving the necessary beans from the ApplicationContext in the TestContext .

Hope this helps!

Sam ( author of the Spring TestContext Framework )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM