gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:45:02 24 4
gpt4 key购买 nike

目前,我正在尝试在静态上下文中获取从 BaseTest 继承的任何基础类的类名。所以为了解释我正在写一个基类它确实使用了 junit 的 @BeforeClass。这里的问题是我在类的所有测试之前启动了一个假的应用程序,它在内存中有自己的 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");
}

例如一些 child 测试:

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

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

最佳答案

我找到了使用“@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);
...
}

关于java - 从它的父级获取静态上下文中的测试类名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55844391/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com