从父级获取静态上下文中的测试类名称

目前,我正在尝试在静态上下文中获取从 BaseTest 继承的任何底层类的类名。因此,为了解释,我正在编写一个使用@BeforeClassjunit 的基类。这里的问题是我在类的所有测试之前启动了一个假应用程序,它拥有自己的内存 h2 数据库。我想将数据库命名为测试类,以便稍后可以查看每次测试写入数据库的内容。


基础测试:


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");

}

例如一些儿童测试:


public class FooTest extends BaseTest{

     @Test 

     public void testFoo(){

     }

}

我已经尝试了几件事,据我所知这是不可能的。但我只需要问是否有什么我还不知道的。


慕村9548890
浏览 149回答 1
1回答

元芳怎么了

我找到了使用 '@ClassRule' 并实现 customg 的解决方案TestWatcher。由于在方法starting(Description description)之前被调用,@BeforeClass public static void beforeClass()我可以像这样使用它:这是我的代码:public abstract class BaseTest {&nbsp; &nbsp; @ClassRule&nbsp; &nbsp; public static CustomTestWatcher classWatcher = new CustomTestWatcher();&nbsp; &nbsp; private static Map<String, String> testConfig;&nbsp; &nbsp; private static FakeApplication fakeApplication;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public static class CustomTestWatcher extends TestWatcher {&nbsp; &nbsp; &nbsp; &nbsp; private String className = BaseTest.class.getSimpleName();&nbsp; &nbsp; &nbsp; &nbsp; public String getClassName() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return className;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; private void setClassName(String className) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.className = className;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; protected void starting(Description description) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //This will set className to = FooTest!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setClassName(description.getClassName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("\nStarting test class: " + className);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; @BeforeClass&nbsp; &nbsp; public static void beforeClass() {&nbsp; &nbsp; &nbsp; &nbsp; //Here now finally is FooTest!&nbsp; &nbsp; &nbsp; &nbsp; String className = classWatcher.getClassName();&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Creating Test Database and Fake Application for " + className);&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java