如何使用Mockito / Powermock模拟一个枚举单身班? [英] How to mock an enum singleton class using Mockito/Powermock?
问题描述
我不确定如何模拟一个枚举单身人士类。
I am unsure on how to mock an enum singleton class.
public enum SingletonObject{
INSTANCE;
private int num;
protected setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
我想在上面的例子中存放getNum(),但是我不能弄清楚如何模拟实际的SingletonObject类。我认为使用Powermock来准备测试将有助于枚举本质上是最终的。
I'd like to stub getNum() in the above example, but I can't figure out how to mock the actual SingletonObject class. I thought using Powermock to prepare the test would help since enums are inherently final.
//... 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。
This is using PowerMockMockito 1.4.10 and Mockito 1.8.5.
推荐答案
如果你想扼杀INSTANCE返回的内容,你可以做到这一点,但这很糟糕(使用反射和放大;字节码操作)。我创造了&使用PowerMock 1.4.12 / Mockito 1.9.0测试了一个使用三个类的简单项目。所有课程都在同一个包中。
If you want to stub out what INSTANCE returns, you can do it but it's kind of nasty (using reflection & bytecode manipulation). I created & tested a simple project with three classes using the PowerMock 1.4.12 / Mockito 1.9.0. All classes were in the same package.
public enum SingletonObject {
INSTANCE;
private int num;
protected void setNum(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
SingletonConsumer.java
SingletonConsumer.java
public class SingletonConsumer {
public String consumeSingletonObject() {
return String.valueOf(SingletonObject.INSTANCE.getNum());
}
}
SingletonConsumerTest.java
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
。
The call to the Whitebox.setInternalState
replaces INSTANCE
with a mock object that you can manipulate within your test.
这篇关于如何使用Mockito / Powermock模拟一个枚举单身班?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!