java 如何使用 PowerMockito 模拟构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41110804/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 05:40:55 来源:igfitidea点击:
How to mock constructor with PowerMockito
提问by Addev
I'm trying to mock a class constructor with PowerMockito for first time, but it doesn't work. My current code is:
我第一次尝试用 PowerMockito 模拟类构造函数,但它不起作用。我目前的代码是:
public class Bar {
public String getText() {
return "Fail";
}
}
public class Foo {
public String getValue(){
Bar bar= new Bar();
return bar.getText();
}
}
@RunWith(PowerMockRunner.class)
@PrepareForTest(Bar.class)
public class FooTest {
private Foo foo;
@Mock
private Bar mockBar;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
PowerMockito.whenNew(Bar.class).withNoArguments().thenReturn(mockBar);
foo= new Foo();
}
@Test
public void testGetValue() throws Exception {
when(mockBar.getText()).thenReturn("Success");
assertEquals("Success",foo.getValue());
}
}
The test fails because the returned value is "Fail". Where is my problem?
测试失败,因为返回值为“Fail”。我的问题在哪里?
回答by Addev
Okey, found the answer, you need to call to
好的,找到答案了,你需要打电话给
@PrepareForTest(Foo.class)
instead of
代替
@PrepareForTest(Bar.class)