试验.我真的需要添加"抛出异常"吗?

cas*_*per 4 java testng unit-testing

我看到人们在测试中使用"抛出异常",但我从未这样做过.我应该担心吗?我从来没有遇到任何问题.有什么不同?

@Test()
public void test() throws Exception
{
        //Do something
}
Run Code Online (Sandbox Code Playgroud)

要么

@Test()
public void test()
{
        //Do something
}
Run Code Online (Sandbox Code Playgroud)

Fre*_*rik 5

如果您正在测试的代码抛出异常,则必须以某种方式处理它.通过在方法签名中声明"抛出异常"或使用try-catch.

如果您在方法中调用的代码没有抛出任何异常,那么您不需要其中任何一个.如果您需要以某种方式捕获异常,编译器将通知您.

另请注意,您可以执行测试以确保抛出异常,请参阅此答案


Mur*_*nik 5

如果该方法抛出异常,对于大多数用例,这本质上与测试失败相同(在某种意义上,以错误状态完成的测试未成功)。许多测试作者不喜欢与处理检查异常相关的麻烦(或代码丑化)。

例如,考虑一个应该运行几个方法并断言对象的最终状态的测试:

public class SomeTest
    SomeObject so;

    @Before
    public void setUp() {
        so = new SomeObject();
    }

    @Test
    public void TestSomeFlow() {
        try {
            so.init();
        // must catch in order to avoid a compilation error
        } catch (InitExceptionIDontCareAbout e) {
            fail ("init failed");
        }

        try {
            so.doSomething();
        // must catch in order to avoid a compilation error
        } catch (SomeOtherExceptionIDontCareAbout e) {
            fail ("doSomething failed");
        }

        assertTrue ("doSomething didn't work", so.isSomethingDone());
    }
}
Run Code Online (Sandbox Code Playgroud)

现在考虑一下如果没有异常处理,代码看起来会干净得多:

public class SomeTest
    SomeObject so;

    @Before
    public void setUp() {
        so = new SomeObject();
    }

    // Any exception throwm will mean the test did not succeed
    @Test
    public void TestSomeFlow() throws Exception {
        so.init();
        so.doSomething();

        assertTrue ("doSomething didn't work", so.isSomethingDone());
    }
}
Run Code Online (Sandbox Code Playgroud)