本文介紹了如何使用 PowerMockito 模擬構(gòu)造函數(shù)的處理方法,對(duì)大家解決問題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我第一次嘗試使用 PowerMockito 模擬類構(gòu)造函數(shù),但它不起作用.我當(dāng)前的代碼是:
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());
}
}
測試失敗,因?yàn)榉祷刂禐镕ail".我的問題在哪里?
The test fails because the returned value is "Fail". Where is my problem?
推薦答案
好的,找到答案了,需要調(diào)用
Okey, found the answer, you need to call to
@PrepareForTest(Foo.class)
而不是
@PrepareForTest(Bar.class)
這篇關(guān)于如何使用 PowerMockito 模擬構(gòu)造函數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請(qǐng)聯(lián)系我們刪除處理,感謝您的支持!