This post is about the shift from manually unit testing your code to enabling automated tests using Assertion Frameworks. This post is intended for audience who are completely new to the discipline of software unit testing.
Let's take a simple example of a Guest Entry system, where
- When a valid guest enters, your system (here shown as the watchman) validates the guest pass (login credentials), and let's the guest enter as an authenticated user
- When an intruder (not a system user) enters, your system should be able to know that the user is invalid and NOT let him enter your system any further
If you are a manual tester or unit tester testing this module / functions of module, then you would want to record it in an excel file like this.
When you wear the hat of a tester, there are 3 things which you need to know
- Example inputs. This is usually given by clients in a call.
- Expected outputs. For each input, the expected output should be known
- The function to call
Hence, in the case of Guest Entry, let's take the example inputs, expected outputs, function to call
- Example inputs: [userId | password] = ["admin" | "nimda"]
- Expected output : returns "Valid Guest"
- Function to Call: GuestLogin(userId, password)
To automate this test case which is already represented in above diagram as excel sheet, we make use of Test Assertion Frameworks
- The Test Assertion Frameworks take Example Inputs, Expected Outputs, Function to call AND compare them with the actual output returned by the function call.
- If the comparison returns true, the test assertion framework declares that the test case has passed.
Irrespective of the assertion framework used, we use the AAA pattern which works with any assertion framework available today
A - Arrange
A - Act
A - Assert
Here is an example of a test case written for testing the function "Add()" using AAA pattern
The above testcase is written using NUnit in .Net. One could choose to use any framework to write the testcases.
There are several Assertion Frameworks available today. Adding some of them for your perusal here.
To be able to be a unit tester, one needs to have the mindset to think like a tester. To think like a tester, one should know only the following things
- Example inputs. This is usually given by clients in a call.
- Expected outputs. For each input, the expected output should be known
- The function to call
Now use the assertion framework of your choice and write testcases for your code.