繁体   English   中英

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

[英]SpringJUnit4ClassRunner - static access to 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对其进行@TestExecutionListeners 然后,侦听器可以通过从TestContextApplicationContext显式检索必要的bean来完成@BeforeClass方法的工作。

希望这可以帮助!

Sam( Spring TestContext Framework的作者

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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