检查JUnit中的异常的最佳做法是什么? [英] What is the best practice for checking exceptions in JUnit?

查看:107
本文介绍了检查JUnit中的异常的最佳做法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力编写测试用例。根据我的阅读,我的测试应该从一开始就失败,我应该努力让测试通过。但是,我发现自己正在编写测试检查边界以及它们应该导致的异常:

I am trying my hand at writing test cases. From what I have read, my tests should fail from the start and I should strive to make tests pass. However, I find myself writing tests checking boundaries and the exceptions they should cause:

@Test(expected=NegativeArraySizeException.class)
public void testWorldMapIntInt() {
    WorldMap w = new WorldMap(-1, -1);
}

@Test(expected=IndexOutOfBoundsException.class)
public void testGetnIntnInt() {
    WorldMap w = new WorldMap(10,10);
    Object o = w.get(-1, -1);
}

但是,默认情况下,此测试会通过,因为Java无论如何都会抛出异常。有没有更好的方法来处理这些预期的异常,可能是默认情况下失败的方式 - 迫使我努力处理这些情况?

However, this test passes by default because Java will throw the exception anyway. Is there a better way to handle these kinds of expected exceptions, possibly a way that fails by default-- forcing me to strive to handle these cases?

推荐答案

我同意你提出的风格不太好。问题是它没有检查抛出异常的方法中的 where ,因此可能会出现漏报。

I agree that the style you present is not so good. The problem is that it doesn't check where in the method the exception is thrown, so it's possible to get false negatives.

我们通常为这样的异常编写测试:

We usually write tests for exceptions like this:

public void testWorldMapIntInt() {
    try {
        WorldMap w = new WorldMap(-1, -1);
        Assert.fail("should have thrown IndexOutOfBoundsException");
    }
    catch (IndexOutOfBoundsException e) {}
}

这篇关于检查JUnit中的异常的最佳做法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆