本文介绍了powermockito:如何在枚举中模拟抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每个常数在枚举中它是一个静态的最终嵌套类。所以要模拟它,你必须在PrepareForTest中使用嵌套类。 MyEnum.values()返回预先初始化的数组,所以它在你的情况下也应该嘲笑。 每个枚举常量只是 public final static 字段。
Each constant in enum it's a static final nested class. So to mock it you have to pointe nested class in PrepareForTest.
MyEnum.values() returns pre-initialised array, so it should be also mock in your case.
Each Enum constant it is just public final static field.
考虑以下(简化)枚举:
Consider the following (simplified) enumeration:
MyEnum { ONE public int myMethod() { // Some complex stuff return 1; }, TWO public int myMethod() { // Some complex stuff return 2; }; public abstract int myMethod(); }这用于以下函数:
void consumer() { for (MyEnum n : MyEnum.values()) { n.myMethod(); } }我现在想写一个单元测试 consumer ,它在每个枚举实例中模拟对myMethod()的调用。我尝试了以下内容:
I'd now like to write a unit test for consumer that mocks out the calls to myMethod() in each of the enumeration instances. I've tried the following:
@RunWith(PowerMockRunner.class) @PrepareForTest(MyEnum.class) public class MyTestClass { @Test public void test() throws Exception { mockStatic(MyEnum.class); when(MyEnum.ONE.myMethod()).thenReturn(10); when(MyEnum.TWO.myMethod()).thenReturn(20); // Now call consumer() }但是正在调用 ONE.myMethod()和 TWO.myMethod()的实际实现。
But the real implementations of ONE.myMethod() and TWO.myMethod() are being called.
我做错了什么?
推荐答案
所有在一起:
@RunWith(PowerMockRunner.class) @PrepareForTest( value = MyEnum.class, fullyQualifiedNames = { "com.stackoverflow.q45414070.MyEnum$1", "com.stackoverflow.q45414070.MyEnum$2" }) public class MyTestClass { @Test public void should_return_sum_of_stubs() throws Exception { final MyEnum one = mock(MyEnum.ONE.getClass()); final MyEnum two = mock(MyEnum.TWO.getClass()); mockStatic(MyEnum.class); when(MyEnum.values()).thenReturn(new MyEnum[]{one, two}); when(one.myMethod()).thenReturn(10); when(two.myMethod()).thenReturn(20); assertThat(new Consumer().consumer()) .isEqualTo(30); } @Test public void should_return_stubs() { final MyEnum one = mock(MyEnum.ONE.getClass()); when(one.myMethod()).thenReturn(10); Whitebox.setInternalState(MyEnum.class, "ONE", one); assertThat(MyEnum.ONE.myMethod()).isEqualTo(10); } }完整示例
更多推荐
powermockito:如何在枚举中模拟抽象方法
发布评论