powermockito:如何在枚举中模拟抽象方法

编程入门 行业动态 更新时间:2024-10-28 14:34:38
本文介绍了powermockito:如何在枚举中模拟抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下(简化)枚举:

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.

我做错了什么?

推荐答案

  • 每个常数在枚举中它是一个静态的最终嵌套类。所以要模拟它,你必须在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.
  • 所有在一起:

    @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:如何在枚举中模拟抽象方法

    本文发布于:2023-10-31 03:48:54,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1544907.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:抽象   方法   如何在   powermockito

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!