简体   繁体   English

模拟静态void方法并更改其行为

[英]Mocking static void method and changing its behaviour

I have a static void method from a different class that is invoked along my code as some sort of logger. 我有一个来自不同类的静态void方法,该方法沿着代码作为某种记录程序被调用。 In order to automatically test the different use cases of my code I was thinking of checking the logs of the system created by such method. 为了自动测试代码的不同用例,我正在考虑检查通过这种方法创建的系统的日志。

What I thought is to mock that class and overwrite the behaviour of the method so that it outputs to System.err . 我想到的是模拟该类并覆盖方法的行为,以便将其输出到System.err Also, redirecting System.err as explained here so that I can easily verify the correct functioning of the code. 另外,按照此处的说明重定向System.err ,以便我可以轻松地验证代码的正确功能。

I do not know how to override the standard behaviour of the method so that it does something (printing to the stderr) instead of what it normally does (by not mocking it) or nothing (what I get my using when(...).thenReturn(...) ) 我不知道如何重写该方法的标准行为,以使其执行某些操作(打印到stderr)而不是通常执行的操作(不模拟它)或什么都不做(我when(...).thenReturn(...)

Mocking static method is not a good way to go, believe me. 相信我,模拟静态方法不是一个好方法。

Altough it is possible with for example PowerMock framework (it is going to replace class loader under the hood), but still it is discouraged. 虽然可以使用例如PowerMock框架(它将在PowerMock替换类加载器)来实现,但是仍然不建议这样做。

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

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