I have an interesting JUnit problem (JUnit 4.12). I have a base class that only has static methods. They must be static due to how they are used. I inherit other classes from the base class. So, if the base class is Base , we have ChildA and ChildB .
Most methods are contained in the base class, but it should know which one it is (just calling the methods as the base class is not valid). This is done through a static data element in the base class:
public class Base { protected static ChildType myType = ChildType.Invalid; ... }
Each child element sets a data member through 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 the name of the configuration).
This works fine when starting the application. After going through it in the debugger and through the log messages, I see that the corresponding types are installed, and the methods load the corresponding configurations based on the child type.
The problem occurs when using JUnit. We have some JUnit tests to test each of the base class methods. Since calling methods only in the base class is not valid, we call methods on the child classes, thus:
bool result = ChildA.methodTwo();
It always doesnβt work. What for? A static initializer is never called. When you run the code as an application, it is 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 does JUnit do that the static initializer skips? Is there any way around this?
More details
In fact, we do not name the method, as I wrote above. I just wanted this example to be as clear as possible. In fact, we have a web service written with the Jersey framework. This method is called one of the REST endpoints.
@POST @Produces(MediaType.TEXT_PLAIN) public String methodPost() { ... return new String( itWorked ? "success" : "fail" ); }
And we call it that (sorry for the ugly syntax, this is how 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 GET tests work, and a static initializer is called for all of them. It is just this POST that fails, and only when running the JUnit test.