如何测试illegalaccessException?

时间:2012-03-22 23:29:07

标签: java junit4

编辑:我想编写一个失败的测试用例,而不是一个积极的测试用例。

我正在为我的Java代码编写测试用例。如何为使用反射api的方法编写测试用例。生成的代码给了我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();
    }
}

谢谢, 斯利拉姆

1 个答案:

答案 0 :(得分:4)

由于反射是被测方法的实现细节,因此您无需专门为其提供支持。要测试此方法,只需执行以下操作:

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