当尝试使用PowerMockRule技术组合Spring测试运行程序和PowerMock运行程序时,每当我尝试使用JPA中的PersistenceContext
注释注入EntityManager
时,我都会从Thoughtworks XStream库中得到一个异常。不使用PowerMockRule
时,同样的测试效果良好。在测试开始时,我还会忽略PowerMockLoader中的所有包。我尝试了@PowerMockIgnore
的各种值,因为这通常可以解决我在PowerMock中遇到的问题,然而,即使忽略了所有包,这个错误仍然会发生。
@PowerMockIgnore("*")
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/test-configuration.xml")
public class SpringAndPowerMockTest {
@Rule
public PowerMockRule rule = new PowerMockRule();
@PersistenceContext
private EntityManager manager;
@Test
public void test() {
}
}
异常如下所示——链接到pastebin上的完整回溯(回溯超过了问题长度的限制):
com.thoughtworks.xstream.converters.ConversionException: Could not call org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.readObject() : Could not call java.util.concurrent.CopyOnWriteArrayList.readObject() : Could not call java.security.CodeSource.readObject() : null
相关持久性单位:
<persistence-unit name="inMemory">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.url" value="jdbc:h2:mem:InMemoryUnitTests;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE" />
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
</properties>
</persistence-unit>
Maven依赖项:
<dependencies>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-easymock</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4-rule</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-classloading-xstream</artifactId>
<version>1.5.1</version>
<scope>test</scope>
</dependency>
</dependencies>
使用Spring 3.2.3.RELEASE
进行测试。请注意,我还测试了spring测试版本3.0.5.RELEASE
,它确实解决了spring/Powermock组合的其他一些错误,但没有解决这个错误。
我遇到了类似的问题,有人建议我创建一个Resources.java类来生成实体管理器。
@Stateful
public class Resources implements Serializable {
@PersistenceContext (type = PersistenceContextType.TRANSACTION)
private EntityManager entityManager;
@Produces
public EntityManager getEntityManager() {
return entityManager;
}
}
我仍然不确定为什么这个解决方案对我有效……但它确实有效。
v/rAce