How would you create a test for a Constructor?

Viewed 143

I'm creating tests for an already complied program, and I'm having trouble getting 100% coverage.

The constructor for a class is:

public Contact(String name, String email){
     if (name == null){
           throw new IllegalAgrugmentException("name must not be null");
     }
}

The test I created reads:

public void testForContactConstructor(){
        Contact testContact = new Contact(null, null);
        assertThrows(IllegalArgumentException.class, () -> {
            testContact.getName();
        });
    }

The test doesn't get covered in eclispe. How would I fix this?

1 Answers

Your assertion seems like it should be

assertThrows(IllegalArgumentException.class, () -> {
  contact = new Contact(null, null);
});

Otherwise it will throw before getting to your assert :(

Other than that i need a little more information, what test framework are you using? There could be annotations missing

All in all you could do something like this (depending on how complex a constructor) :

public void TestContactConstructorFail(){
    assertThrows(IllegalArgumentException.class, () ->
      new Contact(null, null));
}

public void TestContactConstructorSuccess(){
    Contact c = new Contact(name,email);
    assertNotNull(c); //leave the rest for get/set test
}

(add any framework specific annotations as well, e.g. @Test for Junit)

IF you have complex validation or other things in your constructor, i would recommend delegating these to private(ish) methods and testing these separately.

Related