JUnit静态字段的初始化 [英] JUnit initialization of static fields

查看:184
本文介绍了JUnit静态字段的初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JUnit进行单元测试.假设我要测试类B(类B的方法).假设我们还有另一个类A,它是主类(包含main方法)并具有一些protected static字段.

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.

现在,情况是类B使用某些类A的静态字段.因此,如果我正在测试类B,则这些类A的静态字段不存在.

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.

如何在不执行程序(执行类A)的情况下测试类B?

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

我必须澄清一下.假设我们在src/package1/classA.java中具有以下A类:

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.
   }
}

现在假设我们在同一包src/package1/classB.java中有另一个类B.

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....
       }          
}

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

如何在JUnit中手动初始化两个字段classA.field1和classA.field2,而不执行A类的主要方法?

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

推荐答案

您可以调用classA的main方法. ClassA.main(somestrArray),它应该进行初始化.

You could call the main method of classA .i.e. ClassA.main(somestrArray) and it should do the initialization.

但是如果您不想这样做,则可以在与原始类相同的程序包中创建junit测试,并且可以访问受保护的变量. ClassA.field1 = 1;顺便说一句,它不必在同一个项目中,只是程序包名称应该相同.

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.

如果那还不行,那么您将需要重构ClassA以适应这种情况.有执行初始化等的方法.

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.

这篇关于JUnit静态字段的初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆