简体   繁体   English

JUnit静态字段的初始化

[英]JUnit initialization of static fields

I'm using JUnit for unit testing. 我正在使用JUnit进行单元测试。 Let's say I want to test class B (methods of class B ). 假设我要测试B类( B类方法)。 Let's say we have another class A which is the main class (contains main method) and has some protected static fields. 假设我们还有另一个类A ,它是主类(包含main方法),并且具有一些protected static字段。

Now, it is the case that class B uses some of these static fields of class A . 现在,它是该类案件B使用一些类的这些静态字段的A So if I'm testing class B these static fields of class A does not exist. 因此,如果我正在测试B类,则不存在A类的这些静态字段。

How can I test class B without executing the program (executing class A )? 如何在不执行程序的情况下测试B类(执行A类)?

Edit: I have to clarify it. 编辑:我必须澄清它。 Let's assume we have the following class A in src/package1/classA.java: 假设在src / package1 / classA.java中具有以下类A:

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. 现在假设我们在同一包src / package1 / classB.java中有另一个类B。

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. 现在,我在test / package1 / classBTest.java中有一个JUnit测试,用于测试类B。但是问题是field1和field2没有初始化。

How can I manually initialize in JUnit the two fields classA.field1 and classA.field2 without executing the main method of class A? 如何在JUnit中手动初始化两个字段classA.field1和classA.field2,而不执行类A的main方法?

You could call the main method of classA .ie ClassA.main(somestrArray) and it should do the initialization. 您可以调用classA的main方法,即ClassA.main(somestrArray),它应该进行初始化。

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 .ie ClassA.field1 =1; 但是,如果您不想这样做,则可以在与原始类相同的包中创建junit测试,并且可以访问受保护的变量。即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 .ie have a method that does the init etc. 如果那还不行,那么您将需要重构您的ClassA以允许这种情况。即,具有执行init等的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM