java - JUnit 不显示 ExpectedException 消息

标签 java eclipse junit

我在尝试使用 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 界面的样子:

enter image description here

有什么办法可以解决这个问题吗?

最佳答案

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/

相关文章:

eclipse - java.lang.NoSuchFieldError : ROOT at org. apache.tomcat.util.res.StringManager

java - 以编程方式访问 Infinispan MBean

java - MediaPlayer 仅在特定 Activity 开始时继续播放

android - 如何使用 android/eclipse 上的登录页面保持项目始终打开

java - 如何构建多层测试对象?

java - 使用mockito填充列表

hadoop - 具有独立模式的MRUnit

java - 当类扩展抽象类时如何实现构建器模式

java - For 点运算符中的循环计数器

java - Eclipse Google 插件不会为 Web 应用程序启动服务器