When writing unit tests for the below example, would it be best practice to use TestCases (such as in NUnit), or to write multiple tests for verify the functionality?
Say that you want to test the RetrieveContact method below - it simply finds the corresponding Contact within an array and returns the result if found, otherwise will return null.
public class Contact
{
public string Name { get; set; }
}
private static Contact[] Contacts =
{
new Contact() { Name = "Jim" },
new Contact() { Name = "Bob" },
new Contact() { Name = "Tom" }
};
public static Contact RetrieveContact(string name)
{
return Contacts.FirstOrDefault(c => c.Name == name);
}
Would you test this with one method, using TestCases, like below?
[TestCase("Bob", "Bob")]
[TestCase(null, "ZZZ")]
public void Test_RetrievesFromContacts(string expectedName, string name)
{
var ret = RetrieveContact(name);
Assert.AreEqual(expectedName, ret?.Name);
}
Or would you write two separate tests - one for valid contacts, or one for invalid contacts returning null?
[Test]
public void Test_RetrieveValidContact()
{
var ret = RetrieveContact("Bob");
Assert.AreEqual("Bob", ret.Name);
}
[Test]
public void Test_RetrieveInvalidContact()
{
var ret = RetrieveContact("ZZZ");
Assert.AreEqual(null, ret);
}
Thanks
The convention in JUnit is that each unit test should test one specific piece of functionality, one distinct path through the code-under-test. This convention strongly implies that you should not combine multiple, unrelated tests into a single test method.
So, in your example above you would write one test for each of the following:
The rationale for this is:
if firstPathFails then log and move on to second path
etcNotes:
@Before
method thereby reducing the size/reposibilities of each @Test
method.