SuppressStaticInitializationFor(Powermock) [英] SuppressStaticInitializationFor(Powermock)

查看:176
本文介绍了SuppressStaticInitializationFor(Powermock)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个公共类,它具有静态变量,静态块和静态函数。我正在测试我的测试器类中的一个静态函数(例如x),通过在测试器类的类级别(Powermock)使用@SuppressStaticInitializationFor来抑制静态块。现在当我从测试器类运行Jnunit测试时,当控制权到达使用类的静态变量的上述函数时,我得到了空指针异常。所以我的问题是@SuppressStaticInitialization对于类中的静态变量的强制初始化也是如此还是只限于静态块?感谢所有帮助

I have a public class that has static variables, static blocks and static functions. I am testing one of the static function(say x) from my tester class , I have suppressed static block by using @SuppressStaticInitializationFor at the class level(Powermock) in the tester class . Now when I am running Jnunit test from my tester class I am getting null pointer exception when control reaches the above function that is using the static variables of the class.So my question is that does @SuppressStaticInitializationFor supress initialization of static variables too in the class or is it just limited to static blocks ? Any help is appreciated

推荐答案

@SuppressStaticInitialization的文档中说:-

The documentation for @SuppressStaticInitialization says :-


  • 使用此批注抑制一个或多个类的静态初始化程序(构造函数)

这清楚地表明没有提到静态初始化器和变量。

This clearly suggests static initializers and variables havent been mentioned.

但是您必须注意不要传递类名,而必须传递的全限定名。 @suppressStaticInitialization参数中的类

But you must take care that you must not pass the class name but you must pass the fully qualified name of class in parameter of @SuppressStaticInitialization

您需要做的

@SuppressStaticInitialization(com.myPackage.Employee)
public class Employee{
      .....
}

,您不应该这样做

@SuppressStaticInitialization(Employee.class)
    public class Employee{
          .....
    }

希望您正在正确执行此操作。

hope you are doing this correctly.

T静态变量也没有初始化,
的出路是使用 Whitebox 类。您需要执行的步骤是:-

The static variables are also not getting initialized, the way out for this is using the Whitebox class.Steps you need to perform are:-


  • 正常执行抑制操作

  • 使用方法 Whitebox.setInternalState(ClassName.class,fieldName ,fieldValue)转换为所需的值(在测试用例内)

  • 现在您将不会获得空指针异常。

  • Do the suppression normally
  • use the method Whitebox.setInternalState(ClassName.class,fieldName,fieldValue) to whichever value you want, (inside your test case)
  • Now you wont get a null pointer exception.

希望这会有所帮助!

祝你好运!

这篇关于SuppressStaticInitializationFor(Powermock)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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