cam*_*boy -1 java unit-testing
嗨我正在尝试测试一个有异常的代码,但是当我尝试测试它时,它说预期的属性未定义为注释类型测试
package Lab1;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import junit.framework.Assert;
class MyMathTest {
MyMath m = new MyMath();
@Test
void testDiv() {
int actual = m.div(6, 2);
int expected = 3;
assertEquals(expected, actual);
}
/* the error is in the upcoming line*/
@Test (expected = IllegalArgumentException.class)
public void testDivException(){
m.div(5, 0);
}
}
Run Code Online (Sandbox Code Playgroud)
这是错误信息
对于注释类型测试,未定义预期属性
您正在使用JUnit 5但尝试使用JUnit 4的功能.不要混合它们.
import org.junit.jupiter.api.Test;
Run Code Online (Sandbox Code Playgroud)
@TestJUnit5中的注释不支持您尝试使用的内容.
要断言异常,您需要这样做
Assertions.assertThrows(IllegalArgumentException.class, () -> m.div(5, 0));
Run Code Online (Sandbox Code Playgroud)
不要忘记导入包 org.junit.jupiter.api.Assertions
有关JUnit 5的更多信息
您正在使用 JUnit 4 功能,其中您正在做的事情是正确的。
@Test (expected = IllegalArgumentException.class)
public void testDivException(){
m.div(5, 0);
}
Run Code Online (Sandbox Code Playgroud)
但是既然看到你的导入,我就知道你用的是JUnit 5进行测试,我想告诉你,上面的方法是行不通的。由于 JUnit 有自己的断言类来处理相同的问题。我会告诉你如何。
@Test
public void testDivException() {
Assertions.assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
m.div(5, 0);
}
});
}
Run Code Online (Sandbox Code Playgroud)
上述实现适用于 Java 7 及更高版本。现在,如果您想在 Java 8 中使用 Lambda 表达式做同样的事情,请执行以下操作:
@Test
public void testDivException(){
Assertions.assertThrows(IllegalArgumentException.class, () -> m.div(5, 0));
}
Run Code Online (Sandbox Code Playgroud)
您可以在此处阅读有关断言类和 JUnit5 的更多信息。