JUnit/TestNg:如何简化/组合多个 { try failure() catch } 来处理同一异常?
示例(<预期异常>
对于 assert 1
和 assert 2
是相同的):
@junit.framework.Test // or @org.testng.annotations.Test
public void testCase() {
try {
// assert 1
fail();
} catch (<Expected Exception>) {
}
try {
// assert 2
fail();
} catch (<Expected Exception>) {
}
}
Example (<Expected Exception>
for assert 1
& assert 2
is same) :
@junit.framework.Test // or @org.testng.annotations.Test
public void testCase() {
try {
// assert 1
fail();
} catch (<Expected Exception>) {
}
try {
// assert 2
fail();
} catch (<Expected Exception>) {
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果你喜欢冒险,你也可以尝试assertThrows:
https://github.com/dsaff/junit .contrib
如果您有任何问题,请随时询问。
If you're feeling adventurous, you can also try out assertThrows:
https://github.com/dsaff/junit.contrib
Feel free to ask if you have any problems.
如果将其分解为单独的测试方法太困难,那么这就是过去对我有用的方法。
创建一个需要
Callback
的方法expectsException()
。然后,将代码包装在
Callback
中的try {...} catch
块中:但是请注意,这取决于您在
中执行的操作catch
块,这可能会或可能不会比简单的try {...} catch
更详细。(当 Java 获得适当的闭包时,这种方法将变得更有意义。)
If it's too hard to break this up into individual test methods, here's what's worked for me in the past.
Create a method
expectsException()
that expects aCallback
.Then, wrap up the code inside your
try {...} catch
blocks in theCallback
:Note however, that depending on what you're doing in the
catch
block, this may or may not end up less verbose than a straightforwardtry {...} catch
.(When Java gets proper closures, then this approach will make a lot more sense.)
您可能应该将您的方法分成两个单独的方法,每个方法都会抛出:
You should probably break your method into two separate methods that will each throw:
catch-exception 可能会有所帮助:
catch-exception might help: