I will take a shot at this:.
Firstly, I do not see anything incorrect in the manner you have written the test.
Based upon the test case description I assume that the test case is for the AddressBook class which stores a list of contacts and that you are testing the method addContact exposed by the AddressBook class.
That said you can still make your class a bit more robust by doing something like below in the addContact method:
public void addContact(Contact contact) throws IllegalArgumentException
{
if(contact == null)
{
//throw an exception after logging that contact is null
throw new IllegalArgumentException("Passed in contact cannot be null!!")
}
this.contactsList.add(contact);
}
Now your test code for testAddOneContact will have to test two different input cases and this can be done as below using two separate test cases
@Test
public void testAddOneContact() {
final Contact contact = this.context.mock(Contact.class);
this.addressBook.addContact(contact);
assertTrue("Object added to list", this.addressBook.getNumberOfContacts() == 1);
//assuming that Contact class implements the equals() method you can test that the contact
//added is indeed the one that you passed in
assertTrue(addressBook.get(0).equals(contact));
}
//the below test ensures that there is exception handling mechanism within your library code
@Test
@Expected(IllegalArgumentException.class)
public void testShouldThrowWhenContactIsNull()
{
this.addressBook.addContact(null);
}
As an aside - Note how implementing a good test class makes you think about the design of the methods to be exposed as APIs and also how certain methods like hashCode
and equals()
need to be overridden. It also makes you think - 'how do I handle error cases?'. Such thoughtful questions are essential for ensuring that the code you are shipping solves exactly the problem which it is supposed to solve in an efficient and error-free manner.
Hope this helps