本文介紹了如何使用 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)
這篇關于如何使用 PowerMockito 模擬構造函數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!