Search code examples
javajunit

How to check if JUnit test passed


I have written a JUnit test TestClass.test() and I want to know if my test has passed. For example, I might want to delete a video only if a test has passed; Something like

@AfterEach
void afterEach() {
    if (passed) {
        Files.delete(page.video().path());
    }
}

or

if(JUnit.passes(TestClass.test)){
    // Run this code only if my test has passed
}

What is the correct syntax to determine if my JUnit test has passed?


Solution

  • You can programmatically run the tests in a JUnit4 test suite and inspect the result with JUnitCore.runClasses:

    if (JUnitCore.runClasses(MyTests.class).wasSuccessful()) {
      System.err.println("Tests ran successfully.");
    }
    

    Or a single test with:

    if (new JUnitCore().run(Request.method(MyTests.class, "myTest")).wasSuccessful()) {
      System.err.println("Tests ran successfully.");
    }