问题
I have an interesting JUnit problem here (JUnit 4.12). I have a base class that only has static methods. They have to be static, because of the way they're used. I inherit other classes from the base class. So, if the base class is Base
, we have ChildA
and ChildB
.
Most of the methods are contained in the base class, but it has to know which child it actually is (just calling the methods as the base class is invalid). This is done via a static data member in the base class:
public class Base {
protected static ChildType myType = ChildType.Invalid;
...
}
Each child sets the data member via a static initializer, thus:
static {
myType = ChildType.ChildA;
}
Then when the methods are called, the base class knows what type it is and loads the appropriate configurations (the type is actually a configuration name).
This all works perfectly when running the application. Stepping through it in the debugger and through log messages, I can see the appropriate types are set and the methods load the appropriate configurations based on the child type.
The problem arises when using JUnit. We have some JUnit tests to test each of the base class methods. Since calling the methods on just the base class is invalid, we call the methods on the child classes, thus:
bool result = ChildA.methodTwo();
This ''always fails''. Why? The static initializer never gets called. When running the code as an application, it gets called, and everyone is happy. When I run it as a JUnit test, the static initializer is skipped and the methods have invalid data. What is JUnit doing that skips the static initializer? Is there a way around it?
Details
In reality, we're not calling the method as I posted above. I just wanted the example to be as clear as possible. In reality, we have a Web Service written with the Jersey framework. The method called is one of the REST endpoints.
@POST
@Produces(MediaType.TEXT_PLAIN)
public String methodPost() {
...
return new String( itWorked ? "success" : "fail" );
}
And we call it like this (sorry about the ugly syntax, it's just the way it works):
@Test
public void testThePost() throws Exception {
javax.ws.rs.core.Response response = target("restapi/").request().post(Entity.entity(null, MediaType.TEXT_PLAIN));
assertEquals( 200, response.getStatus() );
}
All the GET tests work, and the static initializer is called on all of them. It's just this POST that fails, and only when running the JUnit test.
回答1:
You are trying to implement polymorphic behavior for static methods, a language feature that is present in other programming languages, but is missing in Java.
[
myType
is] a protected member of the base class
Relying on static initializers to set static fields in the base class is very fragile, because multiple subclasses "compete" for a single field in the base class. This "locks in" the behavior of the base class into the behavior desirable for the subclass whose initializer ran last. Among other bad things, it denies a possibility of using multiple subclasses along with the Base
class, and makes it possible for ChildA.methodTwo()
to run functionality designed for ChildB.methodTwo()
. In fact, there is no ChildA.methodTwo()
and ChildB.methodTwo()
, there's only Base.methodTwo()
that relies on information prepared for it by the static initialization sequence.
There are several solutions to this problem. One possibility is to pass Class<Child###>
object to methods of the base class:
class Base {
public static void method1(Class childConfig, String arg) {
...
}
public static void method2(Class childConfig, int arg1, String arg2) {
...
}
}
Now the callers would need to change
ChildA.method1("hello");
ChildA.method2(42, "world");
to
Base.method1(ChildA.class, "hello");
Base.method2(ChildA.class, 42, "world");
Another solution would be to replace static implementation with non-static, and use "regular" polymorphic behavior in conjunction with singletons created in derived classes:
class Base {
protected Base(Class childConfig) {
...
}
public void method1(String arg) {
...
}
public void method2(int arg1, String arg2) {
...
}
}
class ChildA extends Base {
private static final Base inst = new ChildA();
private ChildA() {
super(ChildA.class);
}
public static Base getInstance() {
return inst;
}
... // Override methods as needed
}
class ChildB extends Base {
private static final Base inst = new ChildB();
private ChildB() {
super(ChildB.class);
}
public static Base getInstance() {
return inst;
}
... // Override methods as needed
}
and call
ChildA.getInstance().method1("hello");
ChildA.getInstance().method2(42, "world");
回答2:
There is only one Base.myType
field shared amongst all accessors: Base
, ChildA
and ChildB
. The following sequence of events could cause the failures you are seeing:
- JUnit test invoking
ChildA.methodOne()
starts execution, causing the JVM classloader to loadChildA.class
and execute itsstatic
initializer block, settingBase.myType
toChildType.ChildA
, - JUnit test invoking
ChildB.methodOne()
starts execution, causing the JVM classloader to loadClassB.class
and execute itsstatic
initializer block, settingBase.myType
toChildType.ChildB
, then - JUnit test invoking
ChildA.methodTwo()
starts execution, not executing theChildA
static
initializer block first asChildA
has already been loaded by the JVM classloader, resulting in the JUnit test failing becauseBase.myType
(and thusChildA.myType
) presently equalsChildType.ChildB
.
The basic design issue is that part of your code expects the child types to own the myType
field but that field is in fact shared by all child types.
Please provide the order in which your JUnit tests are being run to verify the above theory. Thanks!
addendum: Thanks for clarifying in comments that you only have one JUnit test invoking just ChildA.methodTwo()
which is only defined in Base
, not ChildA
. What is happening is likely the JVM deciding that ChildA
need not be initialized just to call its parent Base
class's methodTwo()
method. @ShyJ provides a very nice explanation of this for parent and child static
field access at https://stackoverflow.com/a/13475305/1840078. I believe that something similar is happening in your JUnit test.
addendum 2: Below is my code modeling and reproducing the described issue of myType
having the value ChildType.Invalid
during the JUnit test to the best of current understanding:
public enum ChildType {
Invalid, ChildA
}
public class Base {
protected static ChildType myType = ChildType.Invalid;
public static boolean methodTwo() {
return true;
}
}
public class ChildA extends Base {
static {
myType = ChildType.ChildA;
}
}
public class ChildATest {
@org.junit.Test
public void test() {
boolean result = ChildA.methodTwo();
System.out.println("result: " + result);
System.out.println("Base.myType: " + Base.myType);
}
}
Output of execution of ChildATest.test()
:
result: true
Base.myType: Invalid
回答3:
I decided to try what @Arkdiy suggested and have pass-through methods in the child classes.
Let me reiterate: the code, as I had it, works perfectly when run as an application. Only when running via JUnit does it fail.
So now I have something similar to the below:
public class BaseClass {
protected static ChildType myType = ChildType.Invalid;
...
public static boolean methodTwoBase() {
...
}
}
public class ChildA extends BaseClass {
public static boolean methodOne() {
...
}
public static boolean methodTwo() {
myType = ChildType.ChildA;
return methodTwoBase();
}
}
public class ChildB extends BaseClass {
public static boolean methodOne() {
...
}
public static boolean methodTwo() {
myType = ChildType.ChildB;
return methodTwoBase();
}
}
Since I can't override static methods, the version of the method in the base class has a different signature (methodTwoBase()
instead of methodTwo
). I tried it as a regular application and in JUnit and it works both ways.
Kind of an interesting problem, and I blame JUnit. Thanks for all the input!
来源:https://stackoverflow.com/questions/46914409/static-initializer-doesnt-run-during-junit-tests