为什么不调用````''catch(异常'catch(异常)。
我有几分钟之前就有一个问题,但我想尝试其他东西。
例如,我有这样的方法:
//inside Number.java
public static int add(int nr1, int nr2) {
return nr2 + nr2;
}
正如您所看到的,我
在测试中返回了number2 + number2,我会使用它会丢弃它的错误,即预期9而不是在主要方法中计算的数字。
@Test
public void test() throws Exception {
int nr1 = 4;
int nr2 = 5;
int sum = Number.add(nr1, nr2);
assertEquals(9, sum);
}
我现在尝试了此程序,如果程序失败,但不会失败。
@Test
public void test() throws Exception {
int nr1 = 4;
int nr2 = 5;
int sum = Number.add(nr1, nr2);
try {
assertEquals(9, sum);
}catch(Exception e) {
fail("Are you sure you calculate the right numbers?");
}
}
但是该程序只是向我展示了ostertionerror而不是失败()中的消息,
我知道我现在可以这样使用它:
assertEquals("...",9,sum);
但是我不想要这个断言:
expected:<> but was <>
最后
I had the question some minutes before but I want to try something else..
For Example I have this method:
//inside Number.java
public static int add(int nr1, int nr2) {
return nr2 + nr2;
}
As you see I return number2 + number2
In my Test I use that it would throw the error that it was expected 9 instead of the number which was calculate in the main method.
@Test
public void test() throws Exception {
int nr1 = 4;
int nr2 = 5;
int sum = Number.add(nr1, nr2);
assertEquals(9, sum);
}
I tried this now to get an message if the program fails but it doesn´t with fail..
@Test
public void test() throws Exception {
int nr1 = 4;
int nr2 = 5;
int sum = Number.add(nr1, nr2);
try {
assertEquals(9, sum);
}catch(Exception e) {
fail("Are you sure you calculate the right numbers?");
}
}
But the program is only showing me the AssertionError not the Message in fail()
I know now that I can use it this way:
assertEquals("...",9,sum);
but I don't want this AssertionError:
expected:<> but was <>
at the end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
assertionError
扩展了错误
实现throwable
。您是毫无用处的,因为
essertionError
不是异常
。直接使用
catch(assertionError e)
直接捕获它,但通常不应该捕获错误
s。如果您真的想强制呼叫
失败
,请避免使用assertequals
,然后只使用完全避免sastertionError。
An
AssertionError
extendsError
which implementsThrowable
. Youris useless because the
AssertionError
is not anException
.Catch it directly using
catch(AssertionError e)
if you must, but usuallyError
s are not supposed to be caught.If you really want to force a call to
fail
, avoid theassertEquals
and just usewhich avoids the AssertionError altogether.