Get test class name within static context from it's parent

Spektakulatius :

Currently I am trying to get the class name of any underlying class which inherits from BaseTest, within static context. So for explanation I am writing a base-class which does use the @BeforeClass of junit. The problem here is I am starting a fake application before all the tests of the class, with it's own in memory h2 database. I want to name the database as the test class, so I can later see what was written to the database per test.

BaseTest:

public abstract class BaseTest {
private static final Map<String, String> testConfig = getTestConfig();
private static FakeApplication fakeApplication;

@BeforeClass
public static void onlyOnce(){
    fakeApplication = Helpers.fakeApplication(testConfig);
    Helpers.start(fakeApplication);
}

@AfterClass
public static void afterClass(){
    Helpers.stop(fakeApplication);
    fakeApplication = null;
}

private static Map<String, String> getTestConfig() {
    //Here should bee FooTest in this case! But actually it's BaseTest
    String className = MethodHandles.lookup().lookupClass().getSimpleName();
    ...
    configs.put("db.default.url", "jdbc:h2:file:./data/tests/" + className  + ";AUTO_SERVER=TRUE;MODE=Oracle;DB_CLOSE_ON_EXIT=FALSE");
}

And for example some child test:

public class FooTest extends BaseTest{
     @Test 
     public void testFoo(){
     }
}

I already tried several things and as far as I know it's not posssible. But I just need to ask if there's anything I don't know yet.

Spektakulatius :

I found the solution using '@ClassRule' and implemting a customg TestWatcher. As the starting(Description description) is called before the @BeforeClass public static void beforeClass() method I can use it like this:

Here is my code:

public abstract class BaseTest {
    @ClassRule
    public static CustomTestWatcher classWatcher = new CustomTestWatcher();
    private static Map<String, String> testConfig;
    private static FakeApplication fakeApplication;    


    public static class CustomTestWatcher extends TestWatcher {
        private String className = BaseTest.class.getSimpleName();

        public String getClassName() {
            return className;
        }

        private void setClassName(String className) {
            this.className = className;
        }

        @Override
        protected void starting(Description description) {
            //This will set className to = FooTest!
            setClassName(description.getClassName());
            System.out.println("\nStarting test class: " + className);
        }
    }

    @BeforeClass
    public static void beforeClass() {
        //Here now finally is FooTest!
        String className = classWatcher.getClassName();
        System.out.println("Creating Test Database and Fake Application for " + className);
        ...
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=104968&siteId=1