javaspringspring-boottestingjunit

How do a check previous a test execution in jUnit 5?


I need do a validation before execute many test's in a Spring Boot app, with jUnit 5. Basically I need check if my test have a superclass (because we preload context there). I dont want to edit every test else do something that allows me to check before running each test. I did something like this:

public class InheritClassTestCheckExtension implements TestTemplateInvocationContextProvider, BeforeEachCallback {

@Override
public void beforeEach(ExtensionContext context) throws Exception {
    Class<?> superClass = context.getRequiredTestClass().getSuperclass();
    String listClasses = "";
    if (superClass doesnt exists or is object, throw a exception) {
        throw new Exception("Need to inherit from class A,B or C");
   } else { 
       Continue to the test's
   }
}

I have this in my junit-platform.properties

junit.jupiter.extensions.autodetection.enabled=true
junit.jupiter.extensions.autodetection.names=com.my.package.InheritClassTestCheckExtension

But this doesnt work (It's not even entering the method beforeEach). I'm in the correct way? Or what can I use to do it?


Solution

  • junit.jupiter.extensions.autodetection.enabled flag works for the extentions registered via ServiceLoader mechanism https://junit.org/junit5/docs/current/user-guide/#extensions-registration-automatic-enabling

    So, it's expected having the InheritClassTestCheckExtension full class name in META-INF/services/org.junit.jupiter.api.extension.Extension file


    Alternativaly, it's possible using explicit declaration with @ExtendWith or @RegisterExtension annotations,