PowerMock的expectNew()并没有按预期模拟构造函数

我正在尝试学习各种模拟库的细节, PowerMock (特别是EasyMock扩展)是下一个列表。 我试图模拟一个构造函数,当我尝试复制它们时,提供的示例没有相同的响应。 据我所知,它从不嘲笑构造函数,只是继续进行,就像它是正常的一样。

这是测试类:

@RunWith(PowerMockRunner.class) @PrepareForTest({Writer.class}) public class FaultInjectionSituationTest { @Test public void testActionFail() throws Exception { FaultInjectionSituation fis = new FaultInjectionSituation(); PowerMock.expectNew(Writer.class, "test") .andThrow(new IOException("thrown from mock")); PowerMock.replay(Writer.class); System.out.println(fis.action()); PowerMock.verify(Writer.class); } } 

我尝试用EasyMock.isA(String.class)替换“test”,但它产生了相同的结果。

这是FaultInjectionSituation:

 public class FaultInjectionSituation { public String action(){ Writer w; try { w = new Writer("test"); } catch (IOException e) { System.out.println("thrown: " + e.getMessage()); return e.getLocalizedMessage(); } return "returned without throw"; } } 

“作家”只不过是一个类的shell:

 public class Writer { public Writer(String s) throws IOException { } public Writer() throws IOException{ } } 

当测试运行时,它会输出“return without throw”,表示从未抛出exception。

您需要准备正在调用构造函数的类,因此PowerMock知道期望一个模拟的构造函数调用。 尝试使用以下代码更新代码:

 @RunWith(PowerMockRunner.class) @PrepareForTest({Writer.class, FaultInjectionSituation.class}) public class FaultInjectionSituationTest { // as before } 

您需要先创建一个模拟对象:

 Writer mockWriter = PowerMock.createMock(Writer.class) PowerMock.expectNew(Writer.class, "test").andReturn(mockWriter)