gpt4 book ai didi

java - 如何测试非法访问异常?

转载 作者:行者123 更新时间:2023-12-01 19:06:37 25 4
gpt4 key购买 nike

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

我正在为我的 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();
}
}

谢谢,斯里拉姆

最佳答案

因为反射是被测方法的实现细节,所以您不需要专门考虑它。要测试此方法,只需执行以下操作:

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

关于java - 如何测试非法访问异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9832082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com