当前,我正在尝试获取静态上下文中从BaseTest继承的任何基础类的类名。为了说明,我正在写一个基类
确实使用了junit的@BeforeClass
。这里的问题是我在类的所有测试之前启动了一个伪造的应用程序,它在内存h2数据库中拥有。我想将数据库命名为测试类,以便以后可以查看每个测试写入数据库的内容。
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");
}
例如一些子测试:
public class FooTest extends BaseTest{
@Test
public void testFoo(){
}
}
我已经尝试了几种方法,据我所知这是不可能的。 但是我只想问一问我是否还不知道。
答案 0 :(得分:1)
我找到了使用'@ClassRule'并暗示一个定制TestWatcher
的解决方案。由于starting(Description description)
在@BeforeClass public static void beforeClass()
方法之前被调用,我可以这样使用它:
这是我的代码:
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);
...
}