title: JUnit: @Rule's overridden apply method not executed under test
body: <p>I created a JUnit rule to rollback a javax.persistence transaction when any exception occurs (otherwise all further tests will fail since the transaction is in an inconsistent condition). The problem is that my rule will never be executed when the test starts, strictly speaking: the <code>apply</code> method is never executed. it does not even work when I put the @Rule declaration into the concrete class and initialize the transactionRule within the test. Here is how it looks like:</p>
  
  <p><strong>THE RULE</strong></p>
  
  <pre><code>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();
                  }
              }
          }
      }
  }
  </code></pre>
  
  <p><strong>THE ABSTRACT CLASS THAT USES THE RULE</strong></p>
  
  <pre><code>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
  }
  </code></pre>
  
  <p><strong>THE TEST CLASS WITH THE DEFECTIVE TEST</strong></p>
  
  <pre><code>public class RecipePersistenceITest extends AbstractIntegrationTest
  {
      //more tests 
  
      @Test
      public void persistenceOfRecipeWithUserCategorySuccessful()
      {
          //Test that fails
      }
  }
  </code></pre>
  
  <p>Any ideas?</p>