【发布时间】:2017-07-11 12:19:58
【问题描述】:
我正在编写的测试用例:
public class AClassUnderTest {
// This test class has a method call
public Long methodUnderTest() {
// Uses the FinalUtilityClass which contains static final method
FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>);
// 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(<3-parameters-here>) {
}
}
我已经在我的测试类中添加了以下代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ FinalUtilityClass.class })
我想写一个测试用例来模拟它。
我想模拟myStaticFinalMethod() 的调用,以便获得预期的MyBean instatnce,我可以在进一步的代码中使用它来通过我的测试用例。
<3-parameters-here> 是日历、字符串、字符串。
我试过了:
1)
PowerMockito.mock(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>).thenReturn(new MyBean());
2)
PowerMockito.mockStatic(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>).thenReturn(new MyBean());
3)
PowerMockito.spy(FinalUtilityClass.class)
PowerMockito.when(FinalUtilityClass.myStaticFinalMethod(<3-parameters-here>).thenReturn(new MyBean());
但对我没有任何帮助。请建议在final 类中模拟static final 方法的正确方法。
【问题讨论】:
-
你在测试类中添加
@RunWith(PowerMockRunner.class)作为类级别注解了吗? -
当然,我的其他案例运行良好。
-
PowerMockito或PowerMock? -
它的
PowerMockito -
好的,抱歉,那我已经提前回答了,我会删除我的答案。谢谢和抱歉。
标签: java unit-testing powermockito