java - 在 Java 中测试 try-catch block

标签 java unit-testing testing exception

是否有任何可行的方法来测试哪些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);
  • 您希望 nulltext 接收到 “已抛出异常”:

测试:

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/

相关文章:

java - soap ui 生成的代码

java - 线程内的 Guice 注入(inject)器

c++ - 谷歌测试/模拟 Qt 信号

java - JUnit AssertionError - 未引发预期异常

java - Spring 测试 - WebTestClient 无法 Autowiring 。未找到 'WebTestClient' 类型的 beans

java - 关于服务类的几个问题

java类加载器和运行时编译

android - 如何在android中测试振动功能?

python - 我应该如何对启发式算法进行单元测试?

ruby-on-rails - 您如何测试空输入字段?