Joh*_*iou 6 java junit mocking mockito
在一个方法中,我有一个异常被捕获,我想要模拟.
我知道如何使用mock.doSomething()来模拟一个对象抛出一个异常,但是当一个类创建一个新的自身实例时,我需要抛出一个远程异常.
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;
}
Run Code Online (Sandbox Code Playgroud)
我希望能够模拟try块中的所有内容,但我不明白你是如何模拟新类的创建的,具体如下:
bike = new Bicycle(this);
Run Code Online (Sandbox Code Playgroud)
我尝试过许多不同的Mockito测试,例如:
Bicycle b = mock(Bicycle.class);
Mockito.doThrow(new RemoteException()).when(b = new Bicycle());
Run Code Online (Sandbox Code Playgroud)
虽然我明白这会起作用但不起作用,但我想做类似的事情.
我已经阅读了Mockito文档并且没有找到任何有用的东西:
http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html
在这种情况下,您可以使用 Mockito 扩展 PowerMock。它允许模拟构造函数(请参阅https://code.google.com/p/powermock/wiki/MockConstructor)。
在这种情况下,您将编写类似以下测试的内容:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7848 次 |
| 最近记录: |