Home > Software engineering >  JUnit 5 run a method after all tests in every class has run?
JUnit 5 run a method after all tests in every class has run?

Time:09-27

I am trying to run a final method that does some logic after all my tests have completed running. I have seen the extension methods JUnit provides but they seem to all run after each test class

public class Watcher implements BeforeAllCallback, AfterAllCallback {
   public static boolean started = false;

   @Override
   public void beforeAll(ExtensionContext ec) throws Exception {
      if(!started) {
         started = true;
         // Some logic here and this works fine by using the static bool
         System.out.println("Started all");
      }   
   }

   @Override
   public void afterAll(ExtensionContext ec) throws Exception {
      // This runs after each test class I extend on 
         System.out.println("Finished all");
   }
} 

// A Tests

public class ATest : BaseTest {
   @Test
   public void A() {
      System.out.println("A");
      assertTrue(true);
   }
}

// B Tests

public class BTest : BaseTest {
   @Test
   public void B() {
      System.out.println("B");
      assertTrue(true);
   }
}

// My watcher class

@ExtendWith(Watcher.class)
public class BaseTest {
   // Base test class stuff
}

It prints as

  • Started all
  • A
  • Finished all
  • B
  • Finished all

But I want

  • Started all
  • A
  • B
  • Finished all

CodePudding user response:

If you want to do some stuff after all tests, you'll need to implement ExtensionContext.Store.CloseableResource instead of AfterAllCallback.

public class Watcher implements BeforeAllCallback, ExtensionContext.Store.CloseableResource{
   public static boolean started = false;

   @Override
   public void beforeAll(ExtensionContext ec) throws Exception {
      if(!started) {
         started = true;
         // Some logic here and this works fine by using the static bool
         System.out.println("Started all");
      }   
   }


    @Override
    public void close() {
      // This runs after each test class I extend on 
         System.out.println("Finished all");
    }

} 

If you need to execute this for every test class, then you could also use automatic extension registration. https://junit.org/junit5/docs/current/user-guide/#extensions-registration-automatic So your BaseTest can be removed.

  • Related