Java 模拟一个类的所有实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20797396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mock all instances of a class
提问by Zarathustra
I know this is typically a bad practice but in my case it is necessary.
我知道这通常是一种不好的做法,但就我而言,这是必要的。
I have a case where an Enum holds a class to gain some information. So that Enum creates an instance of that calss in its Constructor.
我有一个例子,一个 Enum 持有一个类来获取一些信息。这样 Enum 在其构造函数中创建了该类的一个实例。
public enum MyEnum {
CONSTANT(new MyImpl());
private final MyImpl myImpl;
private MyEnum(final MyImpl impl) {
this.myImpl = impl;
}
public void sayHello() {
System.out.println(this.myImpl.getSomethingToSay());
}
}
MyImpl.java
is just a class with a single method that returns a String.
MyImpl.java
只是一个具有返回字符串的单个方法的类。
public class MyImpl {
public String getSomethingToSay() {
return "Hello!";
}
}
Now finally the unit test:
现在终于单元测试了:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockTestCase;
@RunWith(MockitoJUnitRunner.class)
@PrepareForTest({ MyImpl.class, MyEnum.class })
public class MyEnumTest extends PowerMockTestCase {
@Test
public void testSmth2() throws Exception {
MyImpl impl = Mockito.mock(MyImpl.class);
Mockito.when(impl.getSomethingToSay()).thenReturn("It works!");
PowerMockito.whenNew(MyImpl.class).withAnyArguments().thenReturn(impl);
System.out.println(impl.getSomethingToSay());
System.out.println(new MyImpl().getSomethingToSay());
MyEnum.CONSTANT.sayHello();
}
}
The output is:
输出是:
It works!
Hello!
Hello!
But should be 3 times it works!
但应该是3倍才有效!
采纳答案by Zarathustra
I found the faulty part.
我找到了有问题的部分。
I changed
我变了
@RunWith(MockitoJUnitRunner.class)
to
到
@RunWith(PowerMockRunner.class)
Now the mocking works. But i have to say that as Jon Skeet printed out, the enum does not have everywhere that mocked member-instance. So in another Unit test calling MyEnum.CONSTANT.sayHello();
will print again it works
instead of Hello!
.
现在嘲笑工作。但我不得不说,正如 Jon Skeet 打印出来的那样,枚举并没有到处都有嘲笑的成员实例。因此,在另一个单元测试中,调用MyEnum.CONSTANT.sayHello();
将再次打印it works
而不是Hello!
.