Spring 的@DirtiesContext 导致 Hibernate 异常

Spring's @DirtiesContext leads to Hibernate exception

我有一个 JUnit 集成测试,用于测试 Apache CXF 网络服务的稳定性。该测试继承了 webserviceTestclient ,它对端点进行真正的 Web 服务调用。为了模拟应用程序中的错误,我模拟了一个端点依赖项来引发异常。

这里的挑战是:如何重置端点的依赖项或如何重新创建 Spring 的应用程序上下文,以便后续测试 运行 使用干净的上下文和未模拟的 bean 正确地进行测试。到目前为止我的最佳方法:

Versions used: Spring 3.2.3, Hibernate 4.2.5, Mockito 1.9.5

测试方法:

@Override
public boolean foo() throws FooException
{
    try
    {
        return this.someService.foo();
    }
    catch (Exception exception)
    {
        throw this.convertToFooException(exception);
    }
}

JUnit 测试:

public class IntegrationTest extends WebserviceTestbase
{
    @InjectMocks
    private ClassToTest classToTest;

    @Mock
    private SomeService someServiceMock;

    @Test
    @DirtiesContext
    public void thisTestFails()
    {
        // given
        when(this.someServiceMock.foo().thenThrow(new RuntimeException());

        try
        {
            // when
            this.webserviceTestclient.foo();

            fail();
        }
        catch (FooException FooException)
        {
            // then test passed
        }
    }
}

当我执行上面的测试时,测试失败并且我得到以下堆栈跟踪:

org.springframework.transaction.TransactionSystemException: Could not roll back JPA transaction; nested exception is javax.persistence.PersistenceException: unexpected error when rollbacking
    at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:543)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:846)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:823)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:588)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:297)
    at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:192)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:395)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:91)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access[=13=]0(ParentRunner.java:58)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: javax.persistence.PersistenceException: unexpected error when rollbacking
    at org.hibernate.ejb.TransactionImpl.rollback(TransactionImpl.java:109)
    at org.springframework.orm.jpa.JpaTransactionManager.doRollback(JpaTransactionManager.java:539)
    ... 25 more
Caused by: org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.stat.spi.StatisticsImplementor]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:126)
    at org.hibernate.internal.SessionFactoryImpl.getStatisticsImplementor(SessionFactoryImpl.java:1480)
    at org.hibernate.internal.SessionFactoryImpl.getStatistics(SessionFactoryImpl.java:1476)
    at org.hibernate.engine.transaction.internal.TransactionCoordinatorImpl.afterTransaction(TransactionCoordinatorImpl.java:140)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.afterTransactionCompletion(JdbcTransaction.java:138)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.rollback(AbstractTransactionImpl.java:214)
    at org.hibernate.ejb.TransactionImpl.rollback(TransactionImpl.java:106)
    ... 26 more

希望大家帮帮忙。

此致!

作为一个为我工作的肮脏方式解决方案,我现在通过反射更改了依赖关系:

@Autowired
private ClassToTest classToTest;

private SomeService someServiceBean;


@Override
@Before
public void setup()
{
    super.setup();

    // remember the currect dependency and replace it with null to provoke a RuntimeException
    this.someServiceBean = (SomeService ) ReflectionTools.getFieldValue(this.classToTest, "someService");
    ReflectionTools.setFieldValue(this.classToTest, "someService", null);
}


@Test
public void thisTestNowPasses()
{
    // given

    try
    {
        // when
        this.webserviceTestclient.foo();

        fail();
    }
    catch (FooException FooException)
    {
        // then test passed
    }
}


@Override
@After
public void cleanup()
{
    super.cleanup();

    // restore the dependency so other tests won't fail
    ReflectionTools.setFieldValue(this.classToTest, "someService", this.someServiceBean);
}

反射工具如下:

public class ReflectionTools
{
    public static Object getFieldValue(Object instanceToInspect, String fieldName)
    {
        Object fieldValue = null;

        try
        {
            Field declaredFieldToGet = instanceToInspect.getClass().getDeclaredField(fieldName);
            declaredFieldToGet.setAccessible(true);
            fieldValue = declaredFieldToGet.get(instanceToInspect);
            declaredFieldToGet.setAccessible(false);
        }
        catch (Exception exception)
        {
            String className = exception.getClass().getCanonicalName();
            String message = exception.getMessage();
            String errorFormat = "\n\t'%s' caught when getting value of field '%s': %s";
            String error = String.format(errorFormat, className, fieldName, message);
            Assert.fail(error);
        }

        return fieldValue;
    }


    public static void setFieldValue(Object instanceToModify, String fieldName, Object valueToSet)
    {
        try
        {
            Field declaredFieldToSet = instanceToModify.getClass().getDeclaredField(fieldName);
            declaredFieldToSet.setAccessible(true);
            declaredFieldToSet.set(instanceToModify, valueToSet);
            declaredFieldToSet.setAccessible(false);
        }
        catch (Exception exception)
        {
            String className = exception.getClass().getCanonicalName();
            String message = exception.getMessage();
            String errorFormat = "\n\t'%s' caught when setting value of field '%s': %s";
            String error = String.format(errorFormat, className, fieldName, message);
            Assert.fail(error);
        }
    }
}

希望这对某人有所帮助。