I have several junit test cases that extend an AbstractTest. They're all required to have a static method 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
. 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开发者_JAVA技巧 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 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, i.e., you can have only one instance of it somewhere and use it to obtain interesting reflective metadata, including this one. Without any special ugliness about it. The reason a plain SecurityManager
doesn't work here is that getClassContext
is 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);
}
}
A variation on what @Killian Foth suggested is:
public static junit.framework.Test suite() {
class Inner {} // to get a handle on this class
return new junit.framework.JUnit4TestAdapter(
Inner.class.getEnclosingClass());
}
If you're not afraid of really, really ugly code, try:
Class thisClass = new Object() { }.getClass().getEnclosingClass();
return new junit.framework.JUnit4TestAdapter(thisClass);
Another idea would be to look in the stack trace, i.e. Thread.currentThread().getStackTrace()[2].getClassName() should give you the name for the classs, if the static method has been copied.
精彩评论