我使用 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/