简体   繁体   English

模拟一个类的所有静态void方法

[英]Mock all static void methods of a class

I am using Mockito along with PowerMock to mock the static methods of a class. 我将Mockito和PowerMock一起使用来模拟类的静态方法。 I have provided an example below: 我在下面提供了一个示例:

PowerMock.mockStatic(SampleClass.class);
SampleClass.doNothing();
EasyMock.expectLastCall().once();

This code mocks the doNothing() methods for once. 这段代码只模拟一次doNothing()方法。 However, I have other static void methods in the same class. 但是,我在同一类中还有其他静态void方法。 If any attempt is made to call them then, an exception is thrown. 如果尝试调用它们,则会引发异常。

I have two questions: 我有两个问题:

  1. Do I need to mock all the static methods in the class by copying line 2 and 3 for each method? 我需要通过为每个方法复制第2行和第3行来模拟类中的所有静态方法吗? Is there any other simpler way to mock all the methods in a line or two? 还有其他更简单的方法可以在一两行中模拟所有方法吗?
  2. If my method is a static void method and I want to provide another implementation when the method is called (eg my method closes PreparedStatement, ResultSet and Connection and I want to mock it by closing only PreparedStatement and ResultSet) then, is it possible? 如果我的方法是静态的void方法,并且我想在调用该方法时提供另一种实现(例如,我的方法关闭PreparedStatement,ResultSet和Connection,并且我想仅通过关闭PreparedStatement和ResultSet对其进行模拟),这可能吗?

Thanks all in advance. 提前谢谢大家。

  1. If you are calling other static methods then you have to set expectation for those method as well (step 2 and 3 in your example). 如果要调用其他静态方法,则还必须为这些方法设置期望值(示例中的步骤2和3)。

  2. Can you please provide examples of your code. 您能否提供代码示例。 I am not clear about what you are trying to do. 我不清楚您要做什么。

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

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