简体   繁体   English

在 JUnit-5 中,如何模拟返回 void 的静态方法? 我们可以使用 import org.mockito.MockedStatic 吗?

[英]In JUnit-5, How do I mock a static method that returns void? Can we use import org.mockito.MockedStatic?

I have a few 3rd parties static util methods in my project, some of them just pass or throw an exception.我的项目中有一些 3rd 方静态 util 方法,其中一些只是传递或抛出异常。 There are a lot of examples out there on how to mock a static method using PowerMock but Junit5 doesn't support PowerMock, which has a return type other than void.有很多关于如何使用 PowerMock 模拟静态方法的示例,但 Junit5 不支持 PowerMock,它具有除 void 之外的返回类型。 But how can I mock a static method that returns void to just "doNothing()"?但是,我如何模拟一个将 void 返回到“doNothing()”的静态方法?

Don't mock it.不要嘲笑它。 From your minimal description, you could replace the usage sites with Consumer and provide a mock of that.根据您的最小描述,您可以用Consumer替换使用站点并提供一个模拟。 (You can even initialize the fields with method references to the static methods and just have setter methods to override them.) (您甚至可以使用对静态方法的方法引用来初始化字段,并且只需使用 setter 方法来覆盖它们。)

However, the fact that the class under test calls these static methods is usually just an implementation detail that the test shouldn't care about, only checking observable behavior.然而,被测类调用这些静态方法的事实通常只是测试不应该关心的实现细节,只检查可观察到的行为。

在其上构建一个包装器类,调用包装器方法,如果您可以执行不同的行为,或者可以模拟调用类/方法的包装器,则您可以在测试中使用不同的包装器,

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

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