Java 如何对异常进行单元测试?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3305453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:55:58  来源:igfitidea点击:

How to do unit test for Exceptions?

javajunit

提问by Joseph

As you know, exception is thrown at the condition of abnormal scenarios. So how to analog these exceptions? I feel it is challenge. For such code snippets:

众所周知,异常是在出现异常场景的情况下抛出的。那么如何模拟这些异常呢?我觉得是挑战。对于这样的代码片段:

public String getServerName() {
    try {

        InetAddress addr = InetAddress.getLocalHost();
        String hostname = addr.getHostName();
        return hostname;
    }
    catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}

Does anybody have good ideas?

有人有好的想法吗?

采纳答案by Stephen C

Other answers have addressed the general problem of how to write a unit test that checks that an exception is thrown. But I think your question is really asking about how to get the code to throw the exception in the first place.

其他答案已经解决了如何编写检查是否抛出异常的单元测试的一般问题。但是我认为您的问题实际上是在询问如何让代码首先抛出异常。

Take your code as an example. It would be very hard to cause your getServerName()to internally throw an exception in the context of a simple unit test. The problem is that in order for the exception to happen, the code (typically) needs to be run on a machine whose networking is broken. Arranging for that to happen in a unit test is probably impossible ... you'd need to deliberately misconfigure the machine before running the test.

以您的代码为例。getServerName()在简单的单元测试的上下文中,很难让您在内部抛出异常。问题在于,为了发生异常,代码(通常)需要在网络中断的机器上运行。安排在单元测试中发生这种情况可能是不可能的......在运行测试之前,您需要故意错误配置机器。

So what is the answer?

所以答案是什么?

  1. In some cases, the simple answer is just to take the pragmatic decision and not go for total test coverage. Your method is a good example. It should be clear from code inspection what the method actually does. Testing it is not going to prove anything (except see below **). All you are doing is improve your test counts and test coverage numbers, neither of which should be project goals.

  2. In other cases, it may be sensible to separate out the low-level code where the exception is being generated and make it a separate class. Then, to test the higher level code's handlingof the exception, you can replace the class with a mock class that will throw the desired exceptions.

  1. 在某些情况下,简单的答案就是做出务实的决定,而不是进行全面的测试。你的方法就是一个很好的例子。从代码检查中应该清楚该方法实际做了什么。测试它不会证明任何事情(除了见下文**)。你所做的只是提高你的测试数量和测试覆盖率,这两个都不应该是项目目标

  2. 在其他情况下,将产生异常的低级代码分离出来并使其成为一个单独的类可能是明智的。然后,为了测试更高级别的代码对异常的处理,您可以使用将抛出所需异常的模拟类替换该类。

Here is your example given this "treatment". (This is a bit contrived ... )

这是给出这种“治疗”的例子。(这有点做作……)

public interface ILocalDetails {
    InetAddress getLocalHost() throws UnknownHostException;
    ...
}


public class LocalDetails implements ILocalDetails {
    public InetAddress getLocalHost() throws UnknownHostException {
        return InetAddress.getLocalHost();
    }
}


public class SomeClass {
    private ILocalDetails local = new LocalDetails();  // or something ...
    ...
    public String getServerName() {
        try {
            InetAddress addr = local.getLocalHost();
            return addr.getHostName();
        }
        catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
}

Now to unit test this, you create a "mock" implementation of the ILocalDetailsinterface whose getLocalHost()method throws the exception you want under the appropriate conditions. Then you create a unit text for SomeClass.getServerName(), arranging that the instance of SomeClassuses an instance of your "mock" class instead of the normal one. (The last bit could be done using a mocking framework, by exposing a setterfor the localattribute or by using the reflection APIs.)

现在要对此进行单元测试,您创建ILocalDetails接口的“模拟”实现,其getLocalHost()方法在适当的条件下抛出您想要的异常。然后您为 创build一个单元文本SomeClass.getServerName(),安排 的实例SomeClass使用您的“模拟”类的实例而不是普通的实例。(最后一点可以使用模拟框架,通过setterlocal属性公开 a或使用反射 API 来完成。)

Obviously, you would need to modify your code to make it testable like this. And there are limits to what you can do ... for example, you now cannot create a unit test to make the real LocalDetails.getLocalHost()method to throw an exception. You need to make a case-by-case judgement as to whether it is worth the effort of doing this; i.e. does the benefit of the unit test outweigh the work (and extra code complexity) of making the class testable in this way. (The fact that there is a staticmethod at the bottom of this is a large part of the problem.)

显然,您需要修改代码以使其像这样可测试。而且您可以做的事情是有限的……例如,您现在无法创建单元测试来使真正的LocalDetails.getLocalHost()方法抛出异常。您需要逐案判断是否值得这样做;即单元测试的好处是否超过了使类以这种方式可测试的工作(和额外的代码复杂性)。(事实上​​,static在这底部有一个方法是问题的很大一部分。)



**There isa hypothetical point to this kind of testing. In your example, the fact that the original code catches an exception and returns an empty string couldbe a bug ... depending on how the method's API is specified ... and a hypothetical unit test would pick it up. However, in this case, the bug is so blatant that you would spot it while writing the unit test! And assuming that you fix bugs as you find them, the unit test becomes somewhat redundant. (You wouldn't expect someone to re-instate this particular bug ...)

**这里一个假设点这种测试。在您的示例中,原始代码捕获异常并返回空字符串这一事实可能是一个错误……取决于方法的 API 是如何指定的……并且假设的单元测试会发现它。但是,在这种情况下,该错误非常明显,以至于您在编写单元测试时都会发现它!假设您在发现错误时修复它们,单元测试就变得有些多余了。(你不会期望有人重新修复这个特定的错误......)

回答by Uri

You can tell junit that the correct behavior is to get an exception.

您可以告诉 junit 正确的行为是获取异常。

In JUnit 4, it goes something like:

在 JUnit 4 中,它类似于:

@Test(expected = MyExceptionClass.class) 
public void functionUnderTest() {
    …
}

回答by EndangeredMassa

Many unit testing frameworks allow your tests to expect exceptions as part of the test. JUnit, for example, allows for this.

许多单元测试框架允许您的测试将异常作为测试的一部分。例如,JUnit允许这样做

@Test (expected=IndexOutOfBoundsException.class) public void elementAt() {
    int[] intArray = new int[10];

    int i = intArray[20]; // Should throw IndexOutOfBoundsException
}

回答by Matt

Okay there are a few possible answers here.

好的,这里有几个可能的答案。

Testing for an exception itself is easy

测试异常本身很容易

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

@Test
public void TestForException() {
    try {
        doSomething();
        fail();
    } catch (Exception e) {
        assertThat(e.getMessage(), is("Something bad happened"));
    }
}

Alternately, you can use the Exception Annotation to note that you expect an exception to come out.

或者,您可以使用 Exception Annotation 来指出您希望出现异常。

Now, as to you specific example, Testing that something you are creating inside your method, either via new or statically as you did, when you have no way to interact with the object is tricky. You normally need to encapsulate that particular generator and then use some mocking to be able to override the behavior to generate the exception you expect.

现在,对于您的具体示例,当您无法与对象进行交互时,测试您在方法中创建的内容,无论是通过 new 还是静态方式,都非常棘手。您通常需要封装该特定生成器,然后使用一些模拟来覆盖行为以生成您期望的异常。

回答by Gerhard Burger

Since this question is in community wiki I'll add a new one for completeness: You can use ExpectedExceptionin JUnit 4

由于这个问题在社区 wiki 中,我将添加一个新问题以确保完整性:您可以ExpectedException在 JUnit 4 中使用

@Rule
public ExpectedException thrown= ExpectedException.none();

@Test
public void TestForException(){
    thrown.expect(SomeException.class);
    DoSomething();
}

The ExpectedExceptionmakes the thrown exception available to all test methods.

ExpectedException使得抛出的异常可用于所有测试方法。

Is is also possible to test for a specific error message:

也可以测试特定的错误消息:

thrown.expectMessage("Error string");

or use matchers

或使用匹配器

thrown.expectMessage(startsWith("Specific start"));

This is shorter and more convenient than

这比

public void TestForException(){
    try{
        DoSomething();
        Fail();
    }catch(Exception e) {
      Assert.That(e.msg, Is("Bad thing happened"))
    }
}

because if you forget the fail, the test can result in a false negative.

因为如果你忘记了失败,测试可能会导致假阴性。