Java 如何使用PowerMockito捕获/抛出异常

Java 如何使用PowerMockito捕获/抛出异常,java,junit,Java,Junit,我正在为一个不引发异常的方法编写JUnit测试用例,但这个方法调用了引发ParseException的parse方法,我需要捕获它。我创建了一个测试用例,在其中传递无效的日期格式,在调试过程中,它进入parse方法,然后进入catch块,但是如何在测试用例中显式抛出ParseException,然后在日志中比较字符串呢。希望我清楚 测试中的方法 public static String convertUTC( String strDate, String inputFormat, String

我正在为一个不引发异常的方法编写JUnit测试用例,但这个方法调用了引发ParseException的parse方法,我需要捕获它。我创建了一个测试用例,在其中传递无效的日期格式,在调试过程中,它进入parse方法,然后进入catch块,但是如何在测试用例中显式抛出ParseException,然后在日志中比较字符串呢。希望我清楚

测试中的方法

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;
}
朱尼特

除了上面的测试用例之外,我还想使用PowerMockito显式抛出ParseException,并在日志中进行断言以比较文本。我不能这样做的原因是Converuct不会抛出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的验证。
这对于您的测试用例来说已经足够了。

不清楚您在这里要问什么。如果您想引起ParseException,那么为什么不能在测试用例中传递一个无效字符串呢?这就是我已经提到的。我正在这样做,它将进入方法中的catch块,但我需要在文本中显式抛出exception。请看一下我上面的测试用例,它就是你刚才说的。好的,我明白了。听起来你真正想要的是能够对记录的消息进行断言?是的,我想在消息中做一个断言,我需要编写一个测试用例,在调用convertUTC时,我可以说类似于抛出ParseException的话。如果日期不正确,它将通过记录器,Cobertura甚至会读取它,但我想比较测试用例中的文本。我认为核实是个好主意。你认为这样行吗@SuppressWarningUnchecked@Test public void testCaughtParseException引发异常{PowerMockito.mockStatic DateUtils.class;PowerMockito.when DateUtils.convertUTC any String.class、any String.class、any String.class。然后引发ParseException.class;PowerMockito.verifyStatic times 1;}
public void testCaughtParseException() throws Exception