是否有任何可行的方法来测试哪些Exception
被下面的 Java 方法中的 catch block 捕获,而不更改其当前实现。
public String methodToTest(String text) {
try
{
if (text.contains("something")) {
throw new CustomException();
}
final MyObj myObj = new MyObj(text); //this can throw a MyObjException
return text;
} catch (CustomException e) {
return "An exception has been thrown";
} catch (MyObjException e) {
return "An exception has been thrown";
} catch (Exception e) {
return "An exception has been thrown";
}
}
最佳答案
你不应该测试方法的实现,你应该测试你对方法的期望。以下是您提供的方法的一些示例:
- 您希望包含
"something"
的text
收到"An exception has been throwed"
:
测试:
String result = obj.methodToTest("my_something_string");
assertEquals("An exception has been thrown", result);
- 您希望
null
的text
接收到“已抛出异常”
:
测试:
String result = obj.methodToTest(null);
assertEquals("An exception has been thrown", result);
- 您希望对于
MyObj
无效的text
收到“已抛出异常”
测试:
String result = obj.methodToTest("string_not_valid_for_my_obj");
assertEquals("An exception has been thrown", result);
以同样的方式测试其他预期场景。不要测试实现。
关于java - 在 Java 中测试 try-catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53191807/