JUnit:@ Rule的被覆盖的apply方法未在测试中执行

时间:2015-10-17 10:29:46

标签: java junit rule

我创建了一个JUnit规则,以便在发生任何异常时回滚javax.persistence事务(否则所有进一步的测试都将失败,因为事务处于不一致的情况)。问题是我的规则永远不会在测试开始时执行,严格来说:apply方法永远不会被执行。当我将@Rule声明放入具体类并在测试中初始化transactionRule时,它甚至不起作用。这是它的样子:

规则

public class TransactionRule implements TestRule
{
    private EntityManager entityManager;

    public TransactionRule(EntityManager entityManager)
    {
        this.entityManager = entityManager;
    }

    @Override
    public Statement apply(Statement base, Description description)
    {
        return new TransactionStatement(base);
    }

    public class TransactionStatement extends Statement
    {
        private final Statement runningTest;

        public TransactionStatement(Statement runningTest)
        {
            this.runningTest = runningTest;
        }

        @Override
        public void evaluate() throws Throwable
        {
            try
            {
                runningTest.evaluate();
            }
            catch (Exception e)
            {
                if (entityManager.getTransaction().isActive())
                {
                    entityManager.getTransaction().rollback();
                }
            }
        }
    }
}

使用规则的摘要类

public abstract class AbstractIntegrationTest
{
    //more members vars

    @Rule
    public TransactionRule transactionRule;

    @BeforeClass
    public static void setUpBeforeClass()
    {
        loadProperties();
        entityManagerFactory = Persistence.createEntityManagerFactory("MyCuisinePersistenceTestUnit", connectionProperties);
        entityManager = entityManagerFactory.createEntityManager();
    }

    @Before
    public void setUp()
    {
        transactionRule = new TransactionRule(entityManager);

        entityManager.clear();
    }

    //more code
}

有缺陷测试的测试类

public class RecipePersistenceITest extends AbstractIntegrationTest
{
    //more tests 

    @Test
    public void persistenceOfRecipeWithUserCategorySuccessful()
    {
        //Test that fails
    }
}

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

在使用@Before注释的方法之前调用测试规则,因此尝试在@Before中分配规则将不会产生任何影响(尽管我希望它会引发异常)。

而是在定义上指定规则(并使字段成为最终),并在@Before中执行任何其他配置(如有必要)。

请注意,每个测试方法都在测试类的新实例中执行,因此将规则定义为最终字段是没有问题的。

相关问题