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