java PowerMock 的 expectNew() 没有按预期模拟构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12360555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PowerMock's expectNew() isn't mocking a constructor as expected
提问by AdamSpurgin
I'm trying to learn the ins and outs of various mocking libraries and PowerMock(specifically the EasyMock extension) is next on the list. I'm attempting to mock a constructor and the examples provided don't have the same response when I try to replicate them. As far as I can tell, it never mocks the constructor and just proceeds as if it were normal.
我正在尝试了解各种模拟库的来龙去脉,PowerMock(特别是 EasyMock 扩展)是列表中的下一个。我试图模拟一个构造函数,当我尝试复制它们时,提供的示例没有相同的响应。据我所知,它从不嘲笑构造函数,只是像正常一样继续。
This is the test class:
这是测试类:
@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);
}
}
I've tried replacing the "test" with an EasyMock.isA(String.class), but it yielded the same results.
我试过用 EasyMock.isA(String.class) 替换“测试”,但它产生了相同的结果。
This is the FaultInjectionSituation:
这是 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";
}
}
The "Writer" is nothing more than a shell of a class:
“Writer”只不过是一个类的外壳:
public class Writer {
public Writer(String s) throws IOException {
}
public Writer() throws IOException{
}
}
When the test is run, it prints out "returned without throw", indicating the exception was never thrown.
当测试运行时,它打印出“returned without throw”,表示从未抛出异常。
回答by rrufai
You need to prepare the class that is calling the constructor as well, so PowerMock knows to expect a mocked constructor call. Try updating your code with the following:
您还需要准备调用构造函数的类,因此 PowerMock 知道期待模拟构造函数调用。尝试使用以下内容更新您的代码:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Writer.class, FaultInjectionSituation.class})
public class FaultInjectionSituationTest {
// as before
}
回答by fo_x86
You need to first create a mock object:
您需要先创建一个模拟对象:
Writer mockWriter = PowerMock.createMock(Writer.class)
PowerMock.expectNew(Writer.class, "test").andReturn(mockWriter)