The Intuitive Programmer

Test Driven Development: A lesson in failing first

Function under test

Let’s say we have a function that returns 3 names in a list.

public List<String> listOfNames(){
    return Arrays.asList("John","Jerry","Joseph");
}

To test it, we might write a test like the below.

@Test
@DisplayName("should return a list of names")
public void shouldReturnAListOfNames(){
    List<String> expected=Arrays.asList("John","Jerry","Joseph");
    List<String> actualList=postService.listOfNames();
    assertThat(expected.equals(actualList));
}

Great, your test most likely passed, but is this a good test? Trying modifying a name in the list so that the test reflects the below and run it.

@Test
@DisplayName("should return a list of names")
public void shouldReturnAListOfNames() {
    List <String> expected = Arrays.asList("John", "Jerri","Joseph"); 
    List <String> actualList = postService.listOfNames(); 
    assertThat(expected.equals(actualList));
}

This test also passed. Testing apis have a slew of different methods that serve to provide a more fluent way of writing readable tests. Not only is readability the key, they also serve developers but asserting in a proper manner.

@Test
@DisplayName("should return a list of names")
public void shouldReturnAListOfNames() {
    List <String> expected = Arrays.asList("John", "Jerri","Joseph"); 
    List <String> actualList = postService.listOfNames(); 
    assertEquals(expected,actualList); }

Now your test will fail.

Fail first approach

Test driven development emphasized that the process of a test shows that it fails first before going green. The benefit of such a test is that we are making an assertion that we do not have false positives which can lead to sneaky bugs in our production. True story.

It behoves an aspiring programmer to think of testing as a language. Thinking of your test in terms of Given, When and Then is helpful. Testing is hard, and I believe it’s made that much harder because of such sneaky scenarios. Test wisely friends!

Cheers,

A