序言(请阅读):
的问题是:如何做到这一点(使用 PowerMock )而不从PowerMock获得异常,比如不能实例化该类,因为它是抽象的:
@PrepareForTest({SocketChannel.class})
@RunWith(PowerMockRunner.class)
public class TestThatUsesSocketChannelChannel
{
replace(method(SocketChannel.class, "read", ByteBuffer.class)).with((proxy, method, args) ->
{
// Line below intercepts the argument and manipulates it
((ByteBuffer) args[0]).clear();
});
// The line below throws an exception (because SocketChannel is abstract)
SocketChannel socketChannel = Whitebox.newInstance(SocketChannel.class);
// Once here, ideally I can continue my test
}发布于 2017-09-21 14:50:18
找到了答案:因为SocketChannel是一个抽象类,为了使用Whitebox.newInstance,需要对ConcreteClassGenerator进行初步步骤。这将创建一个具有空方法实现的SocketChannel的运行时子程序。注意,在此之前,我替换了我所关心的方法。结论:这允许我实例化抽象类的子类(一个动态的),而不必显式地扩展它。请参阅上面的代码,现在要使用这样的中间步骤:
@PrepareForTest({SocketChannel.class})
@RunWith(PowerMockRunner.class)
public class TestThatUsesSocketChannelChannel
{
replace(method(SocketChannel.class, "read", ByteBuffer.class)).with((proxy, method, args) ->
{
// Line below intercepts the argument and manipulates it
((ByteBuffer) args[0]).clear();
});
// THIS Fixes it: generate a an on-the-fly class that implements stub methods
// for the ones that are abstract and then (and only then) pass that to Whitebox
Class<?> concreteSocketChannelClass = new ConcreteClassGenerator().createConcreteSubClass(SocketChannel.class);
SocketChannel socketChannel = (SocketChannel) Whitebox.newInstance(concreteSocketChannelClass);
// Once here, ideally I can continue my test
}发布于 2017-09-20 16:21:25
您可以简单地通过使用普通的Mockito来模拟抽象类:
AbstractClass theMock = mock(AbstractClass.class);然后通过PowerMock注入这个抽象类的模拟。
https://stackoverflow.com/questions/46326543
复制相似问题