[英]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.