java - SpringJUnit4ClassRunner - 静态访问EntityManager(Factory)

标签 java spring junit4 entitymanager spring-test

我使用 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。只有在实例化测试类后才能注入(inject)来自 ApplicationContext 的 Bean。

但是,您可以实现自定义 TestExecutionListener(例如,通过扩展 AbstractTestExecutionListener 并覆盖 beforeTestClass(...) 方法)并且通过@TestExecutionListeners 注册它。然后,您的监听器可以通过从 TestContext 中的 ApplicationContext 显式检索必要的 bean,来执行 @BeforeClass 方法的工作。

希望这有帮助!

Sam(Spring TestContext 框架的作者)

关于java - SpringJUnit4ClassRunner - 静态访问EntityManager(Factory),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33018491/

相关文章:

java - 返回到 Spring Batch 中的上一个步骤

junit - 项目中使用log4j和log4j2时找不到配置文件?

unit-testing - Junit:拆分集成测试和单元测试

java - mule Junit 测试代码中出现 "muleContext cannot be resolved"错误

java - 为什么这种带有通配符的方法有效?

java - Spring Boot编码过滤器

java - "file:d:\\dir1\file.xml"和 "file:/d:\\dir1\file.xml"作为 FileSystemXmlApplicationContext 参数

java - Spring @Value 注解方法,当属性不可用时使用默认值

java - 如何通过点击FAB按钮获取id

java - Java TreeSet 和 HashSet 是否期望使用相同的数据给出不同的结果?