Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static initializer doesn't run during JUnit tests

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.

like image 618
Frecklefoot Avatar asked Oct 24 '17 15:10

Frecklefoot


People also ask

How do you initialize a static class in JUnit?

You could call the main method of classA . i.e. ClassA. main(somestrArray) and it should do the initialization. But if you don't want to do that then you could create your junit test in the same package as the original class and you would be able to access the protected variables .

Why is JUnit test ignored?

Sometimes you may require not to execute a method/code or Test Case because coding is not done fully. For that particular test, JUnit provides @Ignore annotation to skip the test. Ignore all test methods using @Ignore annotation.

Can we declare static initializer in local class?

In Java we cannot declare static initializers or member interfaces in a local class (static members can be declared provided there are final and can be initialized at compile time).


2 Answers

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");
like image 68
Sergey Kalinichenko Avatar answered Oct 01 '22 19:10

Sergey Kalinichenko


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 load ChildA.class and execute its static initializer block, setting Base.myType to ChildType.ChildA,
  • JUnit test invoking ChildB.methodOne() starts execution, causing the JVM classloader to load ClassB.class and execute its static initializer block, setting Base.myType to ChildType.ChildB, then
  • JUnit test invoking ChildA.methodTwo() starts execution, not executing the ChildA static initializer block first as ChildA has already been loaded by the JVM classloader, resulting in the JUnit test failing because Base.myType (and thus ChildA.myType) presently equals ChildType.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
like image 41
Mark A. Fitzgerald Avatar answered Oct 01 '22 18:10

Mark A. Fitzgerald