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?

1
  • have you tried Assert.assertNotNull()? Commented Nov 13, 2014 at 17:09

2 Answers 2

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
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can do like this

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.