使用JUnit断言失败

时间:2014-11-13 17:07:14

标签: java unit-testing junit

我有一个属性,我不想成为null。

setter中的Si看起来像这样:

public void setFoo(String bar)
{
    if (bar == null)
        throw new IllegalArgumentException("Should not be null");
    foo = bar;
}

在我的JUnit测试用例中,我想声明如果我执行obj.setFoo(null),它将失败。 我怎么能这样做?

2 个答案:

答案 0 :(得分:2)

JUnit4:

@Test(expected= IllegalArgumentException.class)
public void testNull() {
   obj.setFoo(null);
}

JUnit3:

public void testNull() {
   try {
       obj.setFoo(null);
       fail("IllegalArgumentException is expected");
   } catch (IllegalArgumentException e) {
       // OK
   }
}

答案 1 :(得分:1)

你可以这样做

@Test (expected = IllegalArgumentException.class)
public void setFooTest(){
    myObject.setFoo(null);
}
相关问题