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,487
  • 1
  • 18
  • 36

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
  • 20,071
  • 7
  • 67
  • 86
1

You can do like this

@Test (expected = IllegalArgumentException.class)
public void setFooTest(){
    myObject.setFoo(null);
}
StackFlowed
  • 6,664
  • 1
  • 29
  • 45