Spring的@DirtiesContext导致Hibernate异常

时间:2016-11-17 17:13:11

标签: spring hibernate testing junit integration

我有一个JUnit集成测试,用于测试Apache CXF Web服务的稳定性。测试继承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
        }
    }
}

当我执行上面的测试时,测试失败,我得到以下stacktrace:

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$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.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

希望任何人都可以提供帮助。

祝你好运!

1 个答案:

答案 0 :(得分:0)

作为一种适合我的方法,我现在通过反思改变了依赖性:

@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);
}

以下是ReflectionTools:

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);
        }
    }
}

希望这有助于某人。