使用Mockito创建新类的实例时如何模拟异常 [英] How to mock an exception when creating an instance of a new class using Mockito
问题描述
在一个方法中,有一个我要模拟的异常被捕获.
Within a method, I have an exception being caught which I want to mock.
我知道如何使用ock.doSomething()模拟对象以引发异常,但是当类创建其自身的新实例时,我需要引发远程异常.
I know how to mock an object to throw an exception using mock.doSomething(), but I need to throw a remote exception when a class makes a new instance of itself.
transient Bicycle bike = null;
public Bicycle getBicycle() {
if (bike == null) {
try {
bike = new Bicycle(this);
} catch (RemoteException ex) {
System.out.println("No bikes found");
}
}
return bike;
}
我希望能够模拟try块中的所有内容,但我不理解您如何模拟新类的创建,具体如下几行:
I want to be able to mock everything in the try block, but I don't understand how you mock the creation of a new class, the following line to be specific:
bike = new Bicycle(this);
我尝试了许多不同的Mockito测试,例如:
I have tried many different Mockito tests, such as:
Bicycle b = mock(Bicycle.class);
Mockito.doThrow(new RemoteException()).when(b = new Bicycle());
尽管我知道这会并且不起作用,但我想做类似的事情.
Although I understand this will and is not working, I want to do something similar.
我已经阅读了Mockito文档,但没有发现有用的东西:
I have read the Mockito docs and haven't found anything useful:
http://site.mockito.org/mockito /docs/current/org/mockito/Mockito.html
推荐答案
在这种情况下,您可以使用Mockito扩展程序PowerMock.它允许模拟构造函数(请参见 https://code.google.com/p/powermock /wiki/MockConstructor ).
You can use a Mockito extension, PowerMock, in cases like this. It allows constructors to be mocked (see https://code.google.com/p/powermock/wiki/MockConstructor).
在这种情况下,您将编写类似以下测试的内容:
In this case, you would write something like the following test:
@RunWith(PowerMockRunner.class)
@PrepareForTest({ClassUnderTest.class, Bicycle.class})
public class ConstructorMockingTest
{
@Test
public void getBicycle()
{
ClassUnderTest tested = new ClassUnderTest();
whenNew(Bicycle.class).withArguments(tested).thenThrow(new RemoteException());
Bicycle bicycle = tested.getBicycle();
assertNull(bicycle);
}
}
More examples can be found at: https://code.google.com/p/powermock/source/browse/trunk/modules/module-test/mockito/junit4/src/test/java/samples/powermockito/junit4/whennew/WhenNewTest.java
这篇关于使用Mockito创建新类的实例时如何模拟异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!