[英]use its own class in a static method in Java
I have several junit test cases that extend an AbstractTest. 我有几个junit测试用例,它们扩展了AbstractTest。 They're all required to have a static method suite()
. 它们都必须具有静态方法suite()
。 However people usually copy&paste old test case to make new one, and they end up forgetting to change the old OtherTest.class
to the new one TestA.class
. 但是,人们通常会复制并粘贴旧的测试用例以创建新的用例,而最终忘记将旧的OtherTest.class
更改为新的TestA.class
。 This is bad because the new test will not run, and this is very hard to detect, because there is no compile error. 这很不好,因为新的测试将无法运行,并且由于没有编译错误,因此很难检测到。
public class TestA{
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(
OtherTest.class);// Should be TestA.class
}
}
Is there a way to write something like 有没有办法写像
return new junit.framework.JUnit4TestAdapter(this);
If the above is not possible, are there any other ways to at least mark this type of error? 如果上述方法不可行,是否还有其他方法至少可以标记这种类型的错误?
A variation on what @Killian Foth suggested is: @Killian Foth建议的变体是:
public static junit.framework.Test suite() {
class Inner {} // to get a handle on this class
return new junit.framework.JUnit4TestAdapter(
Inner.class.getEnclosingClass());
}
A further variation: 进一步的变化:
Class thisClass = new SecurityManager() {
public Class getCurrentClass() {
return getClassContext()[1];
}
}.getCurrentClass();
The advantage of this is that you can separate the SecurityManager from the class you're using it in, ie, you can have only one instance of it somewhere and use it to obtain interesting reflective metadata, including this one. 这样做的好处是,您可以将SecurityManager与使用它的类分开,即,您只能在某个位置拥有一个实例,并使用它来获取有趣的反射元数据,包括该元数据。 Without any special ugliness about it. 没有任何特别的丑陋之处。 The reason a plain SecurityManager
doesn't work here is that getClassContext
is protected
. 普通SecurityManager
在这里不起作用的原因是getClassContext
protected
。
edit: further example 编辑:进一步的例子
public class ClassUtil extends SecurityManager {
public static Class getCurrentClass() {
return getClassContext()[1];
}
}
public class TestA {
private static thisClass = ClassUtil.getCurrentClass();
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(thisClass);
}
}
public class TestB {
private static thisClass = ClassUtil.getCurrentClass();
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(thisClass);
}
}
If you're not afraid of really, really ugly code, try: 如果您不害怕真正非常丑陋的代码,请尝试:
Class thisClass = new Object() { }.getClass().getEnclosingClass();
return new junit.framework.JUnit4TestAdapter(thisClass);
另一个想法是查看堆栈跟踪,即,如果已复制静态方法,则Thread.currentThread()。getStackTrace()[2] .getClassName()应该为您提供类的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.