SpringJUnit4ClassRunner语言 - 对EntityManager(Factory)的静态访问



我使用JUnit4和SpringJUnit4ClassRunner编写一些测试类,我需要访问静态方法中的应用程序持久性上下文,一个带有@BeforeClass注释的方法。我的实际代码如下所示:

@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();
    }
    ...
}

我怎么才能做到呢?如果没有 persistence.xml文件,则持久性上下文bean在Spring XML配置文件中配置:

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

提前感谢!

对于JUnit 4,不可能在static @BeforeClass方法中访问Spring bean。只有当测试类被实例化后,ApplicationContext中的bean才能被注入。

然而,你可以实现一个自定义的TestExecutionListener(例如,通过扩展AbstractTestExecutionListener和覆盖beforeTestClass(...)方法)并通过@TestExecutionListeners注册它。然后,侦听器可以通过显式地从TestContext中的ApplicationContext中检索必要的bean来完成@BeforeClass方法的工作。

希望这对你有帮助!

Sam ( Spring TestContext Framework的作者)

最新更新