为什么不调用````''catch(异常'catch(异常)。

发布于 2025-01-21 09:12:05 字数 934 浏览 1 评论 0原文

我有几分钟之前就有一个问题,但我想尝试其他东西。

例如,我有这样的方法:

//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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

狼亦尘 2025-01-28 09:12:05

assertionError扩展了错误 实现throwable。您

catch(Exception e)

是毫无用处的,因为essertionError不是异常

直接使用catch(assertionError e)直接捕获它,但通常不应该捕获错误 s。

如果您真的想强制呼叫失败,请避免使用assertequals,然后只使用

if(sum != 9) {
  fail("Are you sure you calculate the right numbers?");
}

完全避免sastertionError。

An AssertionError extends Error which implements Throwable. Your

catch(Exception e)

is useless because the AssertionError is not an Exception.

Catch it directly using catch(AssertionError e) if you must, but usually Errors are not supposed to be caught.

If you really want to force a call to fail, avoid the assertEquals and just use

if(sum != 9) {
  fail("Are you sure you calculate the right numbers?");
}

which avoids the AssertionError altogether.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文