我无法让这个自定义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.lang.IllegalArgumentException,was: java.lang.IllegalArgumentException
void testMultiply_WhenFourIsMultipiedByZero_ShouldThrowException() {
int i = 0;
int j = 4;
String expectedMsg = "* by zero";
IllegalArgumentException f = new IllegalArgumentException("* by zero");
IllegalArgumentException e = assertThrows("expectedMsg",
IllegalArgumentException.class, () -> {
tm.multiply(i, j);
});
assertEquals("Error", f, e);
}编辑:让它与以下工作。显然,字符串对象不能使用assertEquals进行比较。如果有人能解释原因的话,我会很感激的,但无论如何我还是让它起作用了。
assertTrue(actualMessage.equals(expectedMsg));发布于 2022-11-17 10:00:23
assertEquals("Error", expectedMsg, e);expectedMsg是String的实例&e是IllegalArgumentException类的实例。您正在比较字符串对象和IllegalArgumentException对象。
assertEqual()错误只是显示了这一点。
正确的代码是
assertEquals("Error",expectedMsg,e.getMessage());
https://stackoverflow.com/questions/74473220
复制相似问题