PowerMock模拟创建泛型类的新对象

时间:2017-03-02 14:37:54

标签: java testing mockito powermock powermockito

我需要模拟两个对象的创建

Holder<MyClass1> h1 = new Holder<>();
Holder<MyClass2> h2 = new Holder<>();

我使用Mockito和PowerMock

Holder<MyClass1> mock1 = PowerMockito.spy(new Holder<MyClass1>());
Holder<MyClass2> mock2 = PowerMockito.spy(new Holder<MyClass2>());

PowerMockito.whenNew(Holder.class).withNoArguments().thenReturn(mock1);

如何指定泛型类型来模拟两个不同的对象?我的测试需要2个模拟器。谢谢。

1 个答案:

答案 0 :(得分:0)

一种选择是使用通配符'?',如下:

 Holder<?> holder = new Holder<>();
 Holder<?> mock1 = PowerMockito.spy(holder);
 Holder<?> mock2 = PowerMockito.spy(holder);
 PowerMockito.whenNew(Holder.class).withNoArguments().thenReturn(mock1);