首页 \ 问答 \ 如何使用PowerMockito捕获/抛出异常(How to catch/throw exception using PowerMockito)

如何使用PowerMockito捕获/抛出异常(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并在日志中执行assert来比较文本。 我不能这样做的原因是因为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 );   
}

谢谢。


I am writing JUnit test case for a method which doesn't throw exception but this method invokes parse() method which throws ParseException and I need to catch it. I have created one test case where I am passing invalid date format and during debugging it goes in the parse method and then to the catch block but how can I explicitly throw ParseException in a test case and then compare the String in the log. Hope I am clear.

Method under test.

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 ) );
}

Apart from the above test case I want to explicitly throw ParseException using PowerMockito and do the assert in the log to compare the text. The reason I cannot do it is because converUTC doesn't throw ParseException.

I assume this throws exception but how can I compare the text in the log?

@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 );   
}

Thanks.


原文:https://stackoverflow.com/questions/44442419
更新时间:2023-03-01 11:03

最满意答案

如果你想连续做,为什么你不能只重新塑造你的输入占位符[BATCH, TIME_STEPS, 1]并通过tf.expand_dims(input, 2)在输入中添加一个额外的维度。 这样,你的输入将匹配dynamic_rnn期望的维度(实际上在你的情况下,因为你正在做time_major=True你的输入应该是形状[TIME_STEPS, BATCH, 1])

我很想知道你如何处理从单元格大小到1的输出尺寸切换。现在你有这条线:

decoder_logits = tf.contrib.layers.linear(decoder_outputs, VOCAB_SIZE)

但既然你不再进行分类,那么VOCAB_SIZE只是1? 几天前我在这里问了一个类似的问题,但没有得到任何答复。 我这样做(使用1),但不确定它是否合适(似乎在实践中有点工作,但并不完美)。


If you are trying to do continuous why can't you just reshape your input placeholders to be of shape [BATCH, TIME_STEPS, 1] and add that one extra dimension into your input via tf.expand_dims(input, 2). This way, your input would match the dimensions that dynamic_rnn expects (actually in your case, since you are doing time_major=True your input should be of shape [TIME_STEPS, BATCH, 1])

I'd be curious to know how you'd then handle the switch of the output dimension from your cell size to 1. Right now you have this line:

decoder_logits = tf.contrib.layers.linear(decoder_outputs, VOCAB_SIZE)

But since you are no longer doing a classification, then VOCAB_SIZE is just 1? I asked a similar question here a few days ago, but didn't get any responses. I'm doing it this way (using 1), but not sure whether it's appropriate (seems to sort-of work in practice, but not perfectly).

相关问答

更多

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。