SuppressStaticInitializationFor(Powermock)

编程入门 行业动态 更新时间:2024-10-19 14:37:39
本文介绍了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)

本文发布于:2023-10-31 04:39:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545033.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:SuppressStaticInitializationFor   Powermock

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!