14

我正在尝试了解各种模拟库的来龙去脉,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) 替换“测试”,但它产生了相同的结果。

这是 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";
    }
}

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

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

    public Writer() throws IOException{
    }
}

运行测试时,它会打印出“returned without throw”,表示从未抛出异常。

4

2 回答 2

27

您还需要准备调用构造函数的类,以便 PowerMock 知道期待模拟构造函数调用。尝试使用以下内容更新您的代码:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Writer.class, FaultInjectionSituation.class})
public class FaultInjectionSituationTest { 
 // as before
}
于 2012-09-11T21:46:34.270 回答
2

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

Writer mockWriter = PowerMock.createMock(Writer.class)
PowerMock.expectNew(Writer.class, "test").andReturn(mockWriter)
于 2012-09-10T23:15:38.690 回答