【问题标题】:Assert fail with JUnit [duplicate]JUnit断言失败[重复]
【发布时间】:2015-01-10 22:12:15
【问题描述】:

我有一个属性我不想为空的类。

setter 中的 Si 如下所示:

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

在我的 JUnit 测试用例中,我想断言,如果我执行 obj.setFoo(null),它将失败。 我该怎么做?

【问题讨论】:

  • 你试过Assert.assertNotNull()吗?

标签: java unit-testing junit


【解决方案1】:

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
   }
}

【讨论】:

    【解决方案2】:

    你可以这样做

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2012-12-04
      相关资源
      最近更新 更多