【问题标题】:Java JUnit assertEquals expected:<* by zero> but was:<java.lang.IllegalArgumentException: * by zero>Java JUnit assertEquals expected:<* by zero> 但是:<java.lang.IllegalArgumentException: * by zero>
【发布时间】:2022-11-17 18:00:23
【问题描述】:

我无法让此自定义 JUnit 测试正确处理此自定义异常。只是为了帮助自己理清概念,就实际用途而言没有任何用处。无法弄清楚,也找不到任何直接的在线帮助,所以我想在这里问一下。这是怎么回事?

@Test
    void testMultiply_WhenFourIsMultipiedByZero_ShouldThrowException() {
        int i = 0;
        int j = 4;
        String expectedMsg = "* by zero";

        Exception e = assertThrows(
                expectedMsg,
                IllegalArgumentException.class, () -> {
                    tm.multiply(i, j);
                });

        assertEquals("Error", expectedMsg, e);
//      assertEquals(expectedMsg, expectedMsg, e.getMessage()); //this leads to a different error "Method assertEquals(String, Object, Object) is ambiguous for the type"

    }
public int multiply(int i, int j) throws Exception {
        
        if(i == 0 || j == 0) {
            throw new IllegalArgumentException ("* by zero");
        }
        
        return i * j;
    }

【问题讨论】:

    标签: java testing junit


    【解决方案1】:
    assertEquals("Error", expectedMsg, e);
    

    expectedMsg 是 String 的实例 & e 是 IllegalArgumentException 类的实例。你在比较字符串对象IllegalArgumentException 对象.

    assertEqual() 错误只是显示了这一点。

    正确的代码是

    assertEquals("错误", expectedMsg, e.getMessage());

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-12
      • 2011-06-29
      • 1970-01-01
      • 2017-04-03
      • 1970-01-01
      • 2021-01-09
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多