最终类中的Powermock静态最终方法
我写的测试用例:
public class AClassUnderTest { // This test class has a method call public Long methodUnderTest() { // Uses the FinalUtilityClass which contains static final method FinalUtilityClass.myStaticFinalMethod(); // I want to mock above call so that test case for my "methodUnderTest" passes } }
我有一个最后一堂课。
public final class FinalUtilityClass { /** * Method has 3 parameters */ public static final MyBean myStaticFinalMethod() { } }
我已经在我的测试类中添加了以下代码:
@RunWith(PowerMockRunner.class) @PrepareForTest({ FinalUtilityClass.class })
我想写一个测试用例来嘲笑它。 我想模拟myStaticFinalMethod()
的调用,以便我可以获得预期的MyBean
instatnce,我可以在其他代码中使用它来传递我的测试用例。
是Calendar,String,String。
我尝试过 :
1)
PowerMockito.mock(FinalUtilityClass.class) PowerMockito.when(FinalUtilityClass.myStaticFinalMethod().thenReturn(new MyBean());
2)
PowerMockito.mockStatic(FinalUtilityClass.class) PowerMockito.when(FinalUtilityClass.myStaticFinalMethod().thenReturn(new MyBean());
3)
PowerMockito.spy(FinalUtilityClass.class) PowerMockito.when(FinalUtilityClass.myStaticFinalMethod().thenReturn(new MyBean());
但没有什么对我有用。 请建议在final
类中模拟static final
方法的正确方法。
模拟对静态方法的调用需要以下步骤 :
- 在
@RunWith(PowerMockRunner.class)
的类级别使用@RunWith(PowerMockRunner.class)
注释。 - 在
@PrepareForTest(ClassThatContainsStaticMethod.class)
的类级别使用@PrepareForTest(ClassThatContainsStaticMethod.class)
注释 - 使用
PowerMock.mockStatic(ClassThatContainsStaticMethod.class)
来模拟此类的所有方法
当您按照文档记录这些步骤时,您的测试应该有效。 由于OP似乎对PowerMock与PowerMockito感到困惑 – 这或多或少都是相同的:
PowerMock和PowerMockito基于相同的技术。 他们只是使用不同的“连接器”来使用EasyMock或Mockito。 所以,是的,上面的例子说PowerMock.mockStatic()
– 但是PowerMockito也有mockStatic()
方法。 从这个意义上讲: 核心事物(例如关于注释的准备 )是相同的。 请参阅此处 (它们非常接近,链接的教程说“PowerMock简介” – 虽然它确实引入了PowerMockito。
而你似乎不相信我 – 看这个例子:
package ghostcat.test; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; final class ClassWithStatic { public final static int ignoreMethodCall(String a, String b, int c) { System.out.println("SHOULD NOT SHOW UP: " + a); return c; } } @RunWith(PowerMockRunner.class) @PrepareForTest(ClassWithStatic.class) public class MockStaticTest { @Test public void test() { PowerMockito.mockStatic(ClassWithStatic.class); PowerMockito.when(ClassWithStatic.ignoreMethodCall("a", "b", 5)).thenReturn(42); org.junit.Assert.assertEquals(ClassWithStatic.ignoreMethodCall("a", "b", 5), 42); } }
该测试通过; 并且不打印任何东西。 因此最终的静态方法被嘲笑。