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)
如果该方法抛出异常,junit会将测试标记为处于“错误状态”。对于大多数用例,这本质上与测试失败相同(在某种意义上,以错误状态完成的测试未成功)。许多测试作者不喜欢与处理检查异常相关的麻烦(或代码丑化)。
例如,考虑一个应该运行几个方法并断言对象的最终状态的测试:
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)