如何用嘲弄的Mockito / Powermock枚举单例类?(How to mock an enu

2019-08-21 15:03发布

我是如何嘲笑枚举单例类不确定。

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和1.8.5的Mockito。

Answer 1:

如果您想存根出什么实例,则返回,你能做到这一点,但它(使用反射及字节码操作)有点讨厌。 我创建和测试一个简单的项目,使用PowerMock 1.4.12 / 1.9.0的Mockito三个等级。 所有的类都在同一个包。

SingletonObject.java

public enum SingletonObject {
    INSTANCE;
    private int num;

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

    public int getNum() {
        return num;
    }
}

SingletonConsumer.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());
    }
}

在呼叫Whitebox.setInternalState替换INSTANCE使用模拟对象,您可以将测试范围内操作。



Answer 2:

有你打算嘲笑方法的接口

public interface SingletonInterface {
  int getNum();
}

让枚举实现接口

public enum SingletonObject implements SingletonInterface {
    INSTANCE;
    private int num;

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

    @Override
    public int getNum() {
        return num;
    }
}

嘲笑接口

@Test
public void test() {
  SingletonInterface singleton = Mockito.mock(SingletonInterface.class);
  when(singleton.getNum()).thenReturn(1); //does work
}


文章来源: How to mock an enum singleton class using Mockito/Powermock?