[英]How to catch/throw exception using PowerMockito
我正在為一個不會引發異常的方法編寫JUnit
測試用例,但是此方法將調用引發ParseException
parse()
方法,我需要捕獲它。 我創建了一個測試用例,在其中傳遞無效的日期格式,並在調試過程中將其放入parse方法中,然后傳遞給catch塊,但是如何在測試用例中顯式拋出ParseException
,然后在日志中比較String。 希望我清楚。
被測方法。
public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
String displayDateString = null;
try {
DateFormat inFormat = new SimpleDateFormat( inputFormat );
inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
Date date = inFormat.parse( strDate );
DateFormat outFormat = new SimpleDateFormat( outputFormat );
outFormat.setTimeZone( TimeZone.getDefault() );
displayDateString = formatDate(date, outputFormat);
} catch ( ParseException pe ) {
log.error( "DateUtil.convertUTC :Parse exception while parsing,"+strDate+" using format :"+inputFormat) ;
}
return displayDateString;
}
JUnit的
@Test
public void testConvertUTCParseException() {
String incomingDate = "2012-08-15T22:56:02.038Z";
String inputFormat = "MM/dd/yy hh:mm a z";
String outputFormat = "MM/dd/yy hh:mm a z";
assertEquals( null, DateUtils.convertUTC( incomingDate, inputFormat, outputFormat ) );
}
除了上述測試用例之外,我還想使用PowerMockito顯式拋出ParseException
並在日志中進行斷言以比較文本。 我不能這樣做的原因是因為converUTC不會拋出ParseException。
我認為這會引發異常,但是如何比較日志中的文本?
@SuppressWarnings("unchecked")
@Test
public void testCaughtParseException() throws Exception {
PowerMockito.mockStatic( DateUtils.class );
PowerMockito.when( DateUtils.convertUTC( Mockito.any( String.class ), Mockito.any( String.class ), Mockito.any( String.class ) ) ).thenThrow( ParseException.class );
}
謝謝。
老實說你的測試用例
public void testCaughtParseException() throws Exception
在這里沒有多大意義,因為我們已經在這里嘗試了。 如果您從方法中拋出parseException,則編寫這樣的測試用例是有意義的。 在您的情況下,我想做的是檢查是否在日期不正確的情況下調用log.error。
因此,我建議您使用Mockito的驗證。 這對於您的測試用例就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.