如何使用 Mockito/Powermock 模拟枚举单例类?

新手上路,请多包涵

我不确定如何模拟枚举单例类。

 public enum SingletonObject{
  INSTANCE;
  private int num;

  protected setNum(int num) {
    this.num = num;
  }

  public int getNum() {
    return num;
  }

我想在上面的示例中对 getNum() 进行存根,但我不知道如何模拟实际的 SingletonObject 类。我认为使用 Powermock 准备测试会有所帮助,因为枚举本质上是最终的。

 //... rest of test code
@Test
public void test() {
  PowerMockito.mock(SingletonObject.class);
  when(SingletonObject.INSTANCE.getNum()).thenReturn(1); //does not work
}

这是使用 PowerMockMockito 1.4.10 和 Mockito 1.8.5。

原文由 Sonwright Gomez 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.8k
1 个回答

如果您想清除 INSTANCE 返回的内容,您可以这样做,但它有点讨厌(使用反射和字节码操作)。我使用 PowerMock 1.4.12 / Mockito 1.9.0 创建并测试了一个包含三个类的简单项目。所有课程都在同一个包中。

单例对象.java

 public enum SingletonObject {
    INSTANCE;
    private int num;

    protected void setNum(int num) {
        this.num = num;
    }

    public int getNum() {
        return num;
    }
}

单例消费者.java

 public class SingletonConsumer {
    public String consumeSingletonObject() {
        return String.valueOf(SingletonObject.INSTANCE.getNum());
    }
}

SingletonConsumerTest.java

 import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

@RunWith(PowerMockRunner.class)
@PrepareForTest({SingletonObject.class})
public class SingletonConsumerTest {
    @Test
    public void testConsumeSingletonObject() throws Exception {
        SingletonObject mockInstance = mock(SingletonObject.class);
        Whitebox.setInternalState(SingletonObject.class, "INSTANCE", mockInstance);

        when(mockInstance.getNum()).thenReturn(42);

        assertEquals("42", new SingletonConsumer().consumeSingletonObject());
    }
}

对 --- 的调用将 INSTANCE Whitebox.setInternalState 替换为您可以在测试中操作的模拟对象。

原文由 Matt Lachman 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题