我使用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文件中配置:
<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>提前感谢!
发布于 2016-04-18 16:48:02
使用JUnit 4,不可能在static @BeforeClass方法中访问Spring。只有在实例化了测试类之后,才能注入来自ApplicationContext的been。
但是,您可以实现自定义TestExecutionListener (例如,通过扩展AbstractTestExecutionListener和重写beforeTestClass(...)方法)并通过@TestExecutionListeners注册它。然后,侦听器可以通过显式地从@BeforeClass中的ApplicationContext中检索必要的bean来完成TestContext方法的工作。
希望这能有所帮助!
Sam ( Spring TestContext框架的作者)
https://stackoverflow.com/questions/33018491
复制相似问题