JUnit initialization of static fields

2019-08-08 09:15发布

问题:

I'm using JUnit for unit testing. Let's say I want to test class B (methods of class B). Let's say we have another class A which is the main class (contains main method) and has some protected static fields.

Now, it is the case that class B uses some of these static fields of class A. So if I'm testing class B these static fields of class A does not exist.

How can I test class B without executing the program (executing class A)?

Edit: I have to clarify it. Let's assume we have the following class A in src/package1/classA.java:

public classA {
   protected static int field1;
   protected static int field2;

   public static void main(String[] args) {
      // initialize static fields.
   }
}

Now lets assume we have another class B in the same package src/package1/classB.java.

public ClassB {
       public ClassB() {
            // Do some stuff.
       }

       public void someMethod() {
           // Access of static fields from A.
           classA.field1....
           classA.field2....
       }          
}

Now I have a JUnit test in test/package1/classBTest.java for testing class B. But the problem is that field1 and field2 are not initialized.

How can I manually initialize in JUnit the two fields classA.field1 and classA.field2 without executing the main method of class A?

回答1:

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 .i.e. ClassA.field1 =1; etc. Btw it does not have to be in the same project, just the package names should be the same.

If thats not OK, then you would need to refactor your ClassA to allow for this scenario .i.e. have a method that does the init etc.