【问题标题】:Why PowerMock is attempting to load the server.xml file if the static class is mocked out?如果静态类被模拟出来,为什么 PowerMock 会尝试加载 server.xml 文件?
【发布时间】:2014-04-21 09:58:15
【问题描述】:

我正在尝试对处理消息日志的代码进行单元测试,这会带来很多环境依赖性。此消息记录器是跨团队的所有开发人员使用的框架。我也使用过 PowerMock,因为 Logging 类是静态类。

虽然 Junit 单元测试在使用 Power Mock 后运行绿色,但它仍在尝试加载 server.xml 文件。

类调用如下

单元测试类调用->静态记录器类调用->静态环境类。

这个静态环境类处理加载和解析 server.xml 文件。

我也尝试过以下方法,但即便如此,它还是会加载 xml 文件:

@RunWith(PowerMockRunner.class)

@PrepareForTest({Logger.class,EnvFunctions.class})

PowerMockito.mockStatic(Logger.class);

PowerMockito.mockStatic(EnvFunctions.class);

我是否需要做一些额外的工作才能让它不再尝试加载该文件?

我很想模拟一个静态的 void 类,并尝试使用 doNothing 和 supress。但它不工作

doNothing.when(Logger.class);

suppress(everythingDeclaredIn(Logger.class));

【问题讨论】:

    标签: java unit-testing logging junit powermock


    【解决方案1】:

    感谢您的回复。

    通过上面的解释我能够解决它

    它正在尝试加载 server.xml 文件,因为 Logger.class 有一个静态初始化程序块,它正在调用另一个处理 xml 文件加载的静态方法。

    @SuppressStaticInitializationFor annototation for powermock 成功了

    @RunWith(PowerMockRunner.class)
    
    @PrepareForTest({Logger.class})
    
    @SuppressStaticInitializationFor("org.mycompany.Logger")
    public Class A{
    PowerMockito.mockStatic(Logger.class);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多