即使我已經閱讀了手冊并通過了 Powermock 的多個答案,也無法為我的用例模擬靜態方法。
班級:
@Component
public class SCUtil{
public void createSC(){
try {
String host = InetAddress.getLocalHost().getHostAddress();
// ...
// ...
// ...
} catch (UnknownHostException e) {
log.error("Exception in creasting SC");
throw new ServiceException(e);
}
}
}
測驗類:
@RunWith(PowerMockRunner.class)
@PrepareForTest( InetAddress.class )
public class SCUtilTest {
@InjectMocks
private SCUtil scUtil;
private Event event;
@Before
public void beforeEveryTest () {
event = new InterventionEvent();
}
@Test(expected = ServiceException.class)
public void testCreateSC_Exception () {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException("test"));
scUtil.createSC(event);
}
}
在這里,測驗失敗,因為沒有拋出例外:
java.lang.AssertionError:預期例外:com.example.v1.test.selftest.errorhandling.ServiceException
我已經破壞了幾個多小時,但仍然沒有讓它作業。我究竟做錯了什么?
感謝您提前提供的所有幫助:)
uj5u.com熱心網友回復:
java.net.InetAddress是一個系統類。系統類的呼叫者應該定義在@PrepareForTest({ClassThatCallsTheSystemClass.class}).
請參閱檔案。
不過,模擬系統類的方式與平時有所不同。通常你會準備包含你喜歡模擬的靜態方法(我們稱之為 X)的類,但是因為 PowerMock 不可能準備一個系統類進行測驗,所以必須采取另一種方法。因此,您無需準備 X,而是準備呼叫 X 中的靜態方法的類!
請注意@InjectMocks注解不會注入靜態模擬,它可以被移除。
作業測驗示例:
@RunWith(PowerMockRunner.class)
@PrepareForTest(SCUtil.class)
public class SCUtilTest {
private SCUtil scUtil = new SCUtil();
@Test(expected = ServiceException.class)
public void testCreateSC_Exception () throws UnknownHostException {
PowerMockito.mockStatic(InetAddress.class);
PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException("test"));
scUtil.createSC();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/450112.html
