编辑:我想写一个失败的测试用例,而不是一个正面的.
我正在为我的Java编写测试用例,我为使用反射code.How的方法编写测试用例。得到的代码给了我IllegalAccessException。如何在我的JUnit测试用例中创建一个场景,以便能够测试异常。
public double convertTo(String currency, int amount) {
Class parameters[] = {String.class, int.class};
try {
Method classMethod = clazz.getMethod("convertTo", parameters);
return ((Double) classMethod.invoke(exhangeObject, new Object[]{currency, amount})).doubleValue();
} catch (NoSuchMethodException e) {
throw new CurrencyConverterException();
} catch (InvocationTargetException e) {
throw new CurrencyConverterException();
} catch (IllegalAccessException e) {
System.out.println(e.getClass());
throw new CurrencyConverterException();
}
}谢谢你,斯里拉姆
发布于 2012-03-22 23:32:12
因为反射是被测试方法的实现细节,所以您不需要专门满足它。要测试此方法,只需执行以下操作:
@Test
public void shouldNotThrowException() throws Exception {
testSubject.convertTo("JPY", 100);
}如果有一个CurrencyConverterException抛出,您的测试将失败。
或者,更明确地说:
@Test
public void shouldNotThrowException() {
try {
testSubject.convertTo("JPY", 100);
} catch(CurrencyConverterException e) {
fail(e.getMessage());
}
}注意,当您捕获一个异常并抛出一个新异常时,您应该始终将原始异常链接到新异常中。例如:
} catch (IllegalAccessException e) {
throw new CurrencyConverterException(e);
}编辑:您是在寻找这种模式吗?如何确保引发异常。有两种变体:
// will pass only if the exception is thrown
@Test(expected = CurrencyConverterException.class)
public void shouldThrowException() {
testSubject.doIt();
}或
@Test
public void shouldThrowException() {
try {
testSubject.doIt();
fail("CurrencyConverterException not thrown");
} catch (CurrencyConverterException e) {
// expected
// use this variant if you want to make assertions on the exception, e.g.
assertTrue(e.getCause() instanceof IllegalAccessException);
}
}https://stackoverflow.com/questions/9832082
复制相似问题