0

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!

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136
Matheus Moreira
  • 2,338
  • 4
  • 24
  • 31
  • Just a friendly note that if you find one of the answers to your question acceptable, feel free to [accept it](http://stackoverflow.com/help/accepted-answer) if you want to. – Sam Brannen Sep 10 '16 at 11:29

1 Answers1

1

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 (e.g., 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)

Sam Brannen
  • 29,611
  • 5
  • 104
  • 136