Importance of Unit tests — My journey with Unit-tests 2
I will list my own recent experiences learning C++ data-structures with Unit-tests (using googletest framework) in this post.
For the beginning, I started with Single Linked-Lists with C++. My approach was to write a unit test and the go for the development of that feature, not pure TDD.
1. Identify bugs earlier
In my code-base I tried to add a new node to the list. Following is my code.
#include <cstddef>
class LinkedList{
public:
int value {0};
LinkedList* nextNode {NULL};
};
LinkedList* addNewNode(int nodeVal){
LinkedList *newNode;
newNode->value = nodeVal;
newNode->nextNode = nullptr;
return newNode;
}
Unit test for this feature :
TEST_F(LinkedListTest,addNewNodeReturnsItsNodePointer){
linkedlist = addNewNode(5);
EXPECT_TRUE(linkedlist != nullptr);
ASSERT_EQ(linkedlist->value,5);
EXPECT_TRUE(linkedlist->nextNode != nullptr);
}
When I execute the unit test, I got
Segmentation fault
I tried to sort this thing out my self, but couldn't and finally end-up in stackoverflow. As answer suggested, I forgot to initialize newNode
. But this unit test failure helped me to identify the possible bug.
2 . Identify problems in logic
In next part, I was trying to get the node with the given value in that node. I successfully completed the part when the given value is in the list. But when I wanted to test the failure cases for this logic, I got stuck again.
LinkedList* getANodeWithGivenValue(LinkedList *existingList,int value){ while (existingList != NULL){ if(existingList->value == value){ return existingList;
}
existingList = existingList->nextNode;
}
}
With this logic, unit test kept failing.
TEST_F(LinkedListTest,getANodeWithGivenValueNoMatchingValueReturnsFalse){ LinkedList *existingList = addNewNode(1); LinkedList *nodeWithTheGivenValue = getANodeWithGivenValue(existingList,5); EXPECT_TRUE(nodeWithTheGivenValue->nextNode == nullptr); EXPECT_EQ(nodeWithTheGivenValue->value,0);
}
My expectation was that if `getANodeWithGivenValue` function does not match anything, it will automatically goes to empty node value. My ego was saying that my logic is right, there is an issue in the unit-test.
Finally I understood my issue, `getANodeWithGivenValue` is having an issue for a value not in the list. It just returns the list after finishing while
loop.
This is a short post regarding my issues. Not a well constructed post.