0

I have a class with an attribute I don't want to be null.

Si in the setter looks like this :

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

And in my JUnit test case, I would like to assert that if I do obj.setFoo(null), it will fail. How can I do this?

Eko
  • 1,377
  • 1
  • 16
  • 33

2 Answers2

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
   }
}
sergej shafarenka
  • 19,870
  • 7
  • 66
  • 85
1

You can do like this

@Test (expected = IllegalArgumentException.class)
public void setFooTest(){
    myObject.setFoo(null);
}
StackFlowed
  • 6,604
  • 1
  • 28
  • 44