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?
A? If they are private then classBwill not be permitted to access them, whether using JUnit or otherwise.AfromBso you need to edit your question and provide more information.A.field1andA.field2, and then callbUnderTest.someMethod(). But I agree this is ugly design. Why arent field1 and field2 passed as argument to the method, or to the B constructor? Global, mutable state is something you want to avoid at all cost.