[英]the attribute expected is undefined for the annotation type test
Hi I am trying to test a code that has an exception but when I try to test it it says the attribute expected is undefined for the annotation type test 嗨,我正在尝试测试包含异常的代码,但是当我尝试对其进行测试时,它说注释类型test的预期属性未定义
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);
}
}
And here is the error message 这是错误消息
the attribute expected is undefined for the annotation type test
注释类型测试的预期属性未定义
You are using JUnit 5 but trying to use JUnit 4's features. 您正在使用JUnit 5,但尝试使用JUnit 4的功能。 Don't mix them.
不要混在一起。
import org.junit.jupiter.api.Test;
The @Test
annotation from JUnit5 don't support what you are trying to use. JUnit5中的
@Test
注释不支持您要使用的内容。
To assert exceptions, you need to do 要声明异常,您需要执行
Assertions.assertThrows(IllegalArgumentException.class, () -> m.div(5, 0));
Do not forget to import the package org.junit.jupiter.api.Assertions
不要忘记导入包
org.junit.jupiter.api.Assertions
You are using a JUnit 4 feature in which what you are doing is correct. 您正在使用正确的JUnit 4功能。
@Test (expected = IllegalArgumentException.class)
public void testDivException(){
m.div(5, 0);
}
But since after seeing your import, I can tell that you are using JUnit 5 for testing, I would like to tell you that the above method will not work. 但是由于看到导入后,我可以告诉您正在使用JUnit 5进行测试,所以我想告诉您上述方法将不起作用。 Since JUnit has its own Assertions class to handle the same.
由于JUnit具有自己的Assertions类来处理相同的类。 I will show you how.
我会告诉你如何。
@Test
public void testDivException() {
Assertions.assertThrows(IllegalArgumentException.class, new Executable() {
@Override
public void execute() throws Throwable {
m.div(5, 0);
}
});
}
The above implementation will work with Java 7 and above. 以上实现将与Java 7及更高版本一起使用。 Now if you want to do the same thing using Lambda Expression in Java 8, do this:
现在,如果您想在Java 8中使用Lambda Expression做相同的事情,请执行以下操作:
@Test
public void testDivException(){
Assertions.assertThrows(IllegalArgumentException.class, () -> m.div(5, 0));
}
You can read more about Assertion class and JUnit5 here . 您可以在此处阅读有关Assertion类和JUnit5的更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.