如何使用 PowerMockito 模拟构造函数
我第一次尝试使用 PowerMockito 模拟类构造函数,但它不起作用.我当前的代码是:
I'm trying to mock a class constructor with PowerMockito for first time, but it doesn't work. My current code is:
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());
}
}
测试失败,因为返回值为Fail".我的问题在哪里?
The test fails because the returned value is "Fail". Where is my problem?
推荐答案
好的,找到答案了,需要调用
Okey, found the answer, you need to call to
@PrepareForTest(Foo.class)
而不是
@PrepareForTest(Bar.class)
相关文章