我在尝试使用 JUnit(4) 和 Eclipse(Ubuntu) 运行一些测试时遇到了问题。我有一个简单的测试类,其函数 testEmptyTitle()
如果没有,应该通知我抛出错误
package tests;
import workshop.WorkshopPaper;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class WorkshopPaperTest {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test(expected=IndexOutOfBoundsException.class)
public void testEmptyTitle() {
thrown.expect(IndexOutOfBoundsException.class);
thrown.reportMissingExceptionWithMessage("No exception thrown");
}
}
当我尝试运行测试时,我没有看到“未抛出异常”
消息。
这是运行测试后我的 JUnit 界面的样子:
有什么办法可以解决这个问题吗?
最佳答案
ExpectedException
对于检查测试方法是否抛出异常实例非常有用,并且在您的代码中您没有抛出 IndexOutOfBoundsException
,请查看下面的内容:
@Test//remove expected exception here, it not required
public void testEmptyTitle() throws IndexOutOfBoundsException {
thrown.expect(IndexOutOfBoundsException.class);
thrown.reportMissingExceptionWithMessage("No exception thrown");
throw new IndexOutOfBoundsException();//throw exception here
}
一般来说,@Test(expected=SomeException.class)
或 ExpectedException.expect(SomeException.class)
用于测试方法的异常行为,但不能同时使用两者一起。
你可以看看here ExpectedException
类 API 及其用法的简单示例。
关于java - JUnit 不显示 ExpectedException 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43034312/