JUnit没有显示ExpectedException消息

时间:2017-03-26 20:42:36

标签: java eclipse junit

我在尝试使用JUnit(4)和Eclipse(Ubuntu)运行一些测试时遇到了一个问题。我有一个带有函数scheduleAt(selfMessage, simTime() + SimTime(1, SIMTIME_MS)); 的简单测试类,如果没有抛出错误,它应该通知我

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

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

3 个答案:

答案 0 :(得分:1)

使用预期的异常规则时不需要 data: { labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], datasets: [{ label: 'Limos', data: [ <cfoutput> <cfset step = 0> <cfloop collection="#MonthValues#" item="key"> <cfset step++>#MonthValues[key]#<cfif step lt 12>,</cfif> </cfloop> </cfoutput> ], backgroundColor: "rgba(153,255,51,1)" }, { label: 'Charter Buses', data: [ YOUR DELIMITED DATA FOR CHARTER BUSES HERE ], backgroundColor: "rgba(255,153,0,1)" }] } }); ,并且您也没有调用任何类的实例来抛出异常,甚至只是执行@Test(expected=Class<T>)

答案 1 :(得分:1)

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)用于测试方法的异常行为,但不能同时测试两者。

您可以查看ExpectedExceptionHttpRequest类API及其使用的简单示例。

答案 2 :(得分:0)

您不必将ExpectedException与Expected = IndexOutOfBoundsException.class一起使用 从@Test删除属性期望= IndexOutOfBoundsException.class

@Rule
public ExpectedException thrown = ExpectedException.none(); 
@Test
public void throwsExceptionWithSpecificType() {
     thrown.expect(NullPointerException.class);
     thrown.reportMissingExceptionWithMessage("My MSG");
 }