[英]SpringJUnit4ClassRunner - static access to EntityManager(Factory)
I'm using JUnit4 with SpringJUnit4ClassRunner
to write some test classes and I need to access the application persistence context inside a static method, a method with the @BeforeClass
annotation. 我将JUnit4与
SpringJUnit4ClassRunner
结合使用来编写一些测试类,并且需要在静态方法(带有@BeforeClass
批注的方法)内访问应用程序持久性上下文。 My actual code is seen below: 我的实际代码如下所示:
@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();
}
...
}
How can I accomplish that? 我该怎么做? I do not have a
persistence.xml
file, the persistence context bean is configured inside a Spring XML config file: 我没有
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>
Thanks in advance! 提前致谢!
With JUnit 4 it is not possible to access Spring beans in a static
@BeforeClass
method. 使用JUnit 4,无法以
static
@BeforeClass
方法访问Spring Bean。 Beans from the ApplicationContext
can only be injected once the test class has been instantiated. 只有实例化测试类后,才能注入
ApplicationContext
Bean。
However, you can implement a custom TestExecutionListener
(eg, by extending AbstractTestExecutionListener
and overriding the beforeTestClass(...)
method) and register it via @TestExecutionListeners
. 但是,您可以实现自定义
TestExecutionListener
(例如,通过扩展AbstractTestExecutionListener
并覆盖beforeTestClass(...)
方法),然后通过@TestExecutionListeners
对其进行@TestExecutionListeners
。 Your listener can then do the work of your @BeforeClass
method by explicitly retrieving the necessary beans from the ApplicationContext
in the TestContext
. 然后,侦听器可以通过从
TestContext
的ApplicationContext
显式检索必要的bean来完成@BeforeClass
方法的工作。
Hope this helps! 希望这可以帮助!
Sam ( author of the Spring TestContext Framework ) Sam( Spring TestContext Framework的作者 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.