如何使用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 invokesparse()
method which throwsParseException
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 throwParseException
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
最满意答案
如果你想连续做,为什么你不能只重新塑造你的输入占位符
[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 viatf.expand_dims(input, 2)
. This way, your input would match the dimensions thatdynamic_rnn
expects (actually in your case, since you are doingtime_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).
相关问答
更多-
tf.nn.dynamic_rnn需要批处理(具有minibatch含义)的不相关序列。 cell是您想要使用的实际单元格(LSTM,GRU ...) inputs的形状为batch_size x max_time x input_size ,其中max_time是最长序列中的步数(但所有序列可以具有相同的长度) sequence_length是batch_size大小的向量,其中每个元素给出批处理中每个序列的长度(如果所有序列的大小相同,则将其保留为默认值)。 该参数是定义单元展开大小的参数。 隐藏状态处 ...
-
Tensorflow:如何实现Multilayered dynamic_rnn?(Tensorflow: How to implement Multilayered dynamic_rnn?)[2022-07-03]
如果需要multi-layer LSTM ,可以使用tf.contrib.rnn.MultiRNNCell 。 所以对于两层: n_layers = 2 lstm_stacked = tf.contrib.rnn.MultiRNNCell([lstm_cell() for _ in range(n_layers)]) outputs, final_state = tf.nn.dynamic_rnn(lstm_stacked, X_in, dtype=tf.float32) def lstm_cell() ... -
这应该。 如果您发现问题,请详细描述您所遇到的错误。 It should. If you're seeing problems, please describe the error you're getting in a little more detail.
-
从他的评论中复制@jdehesa的答案以获得更好的可见性: 错误似乎相当清楚, tf.nn.dynamic_rnn期望三维张量作为输入(即等级3),但fc2只有两个维度。 如果你传递time_major=True , fc2的形状应该类似于(
, , ) (或( , , ) ) Copying the answer of @jdehesa from his commen ... -
建议的解决方案适用于我,但Layer.call方法规范更通用,因此以下Wrapper应该对API更改更加健壮。 你这个: class Wrapper(tf.nn.rnn_cell.RNNCell): def __init__(self, inner_cell): super(Wrapper, self).__init__() self._inner_cell = inner_cell @property def state_size(self): return s ...
-
您可以将batch_size指定为占位符,而不是常量。 只需确保在feed_dict提供相关的数字,这对于培训和测试都是不同的 重要的是,将[]指定为占位符的维度,因为如果指定None ,则可能会出现错误,这在其他地方是惯常的。 所以像这样的东西应该工作: batch_size = tf.placeholder(tf.int32, [], name='batch_size') init_state = lstm_cell.zero_state(batch_size, dtype=tf.float32) ou ...
-
您传递的sequence_length参数实际上设置为1而不是2 ,这就是网络无法训练的原因。 len(example)返回1因为它的形状(1,2,1) 。 你可以通过使用len(example.flatten())来解决它,你应该看到正确的输出。 The sequence_length parameter that you are passing is actually set to 1 and not 2and thats why the network is unable to train. len( ...
-
Tensorflow dynamic_rnn传播nans批量大于1(Tensorflow dynamic_rnn propagates nans for batch size greater than 1)[2022-09-11]
我没有把它追溯到确切的操作,但我相信这是事实。 为什么没有忽略sequence_length之外的值? 在进行某些操作时,它们被乘以0 (它们被屏蔽掉)的意义上被忽略。 在数学上,结果总是为零,所以它们应该没有效果。 不幸的是, nan * 0 = nan 。 所以,如果你在你的例子中给出nan值,它们就会传播。 你可能想知道为什么TensorFlow不会完全忽略它们,但只是掩盖它们。 原因是现代硬件上的性能。 在一大块零形状的大规则形状上进行操作要比在几个小形状上进行操作要容易得多(这是从分解不规则形状得 ... -
如果你想连续做,为什么你不能只重新塑造你的输入占位符[BATCH, TIME_STEPS, 1]并通过tf.expand_dims(input, 2)在输入中添加一个额外的维度。 这样,你的输入将匹配dynamic_rnn期望的维度(实际上在你的情况下,因为你正在做time_major=True你的输入应该是形状[TIME_STEPS, BATCH, 1]) 我很想知道你如何处理从单元格大小到1的输出尺寸切换。现在你有这条线: decoder_logits = tf.contrib.layers.linea ...
-
tf.one_hot(length, ...) 这里的长度是一个函数,而不是张量。 尝试长度(东西),而不是。 tf.one_hot(length, ...) here length is a function, not a tensor. Try length(something) instead.