What is Unit Testing? - Unit Testing Explained - AWS (original) (raw)
A unit test is a block of code that verifies the accuracy of a smaller, isolated block of application code, typically a function or method. The unit test is designed to check that the block of code runs as expected, according to the developer’s theoretical logic behind it. The unit test is only capable of interacting with the block of code via inputs and captured asserted (true or false) output.
A single block of code may also have a set of unit tests, known as test cases. A complete set of test cases cover the full expected behavior of the code block, but it’s not always necessary to define the full set of test cases.
When a block of code requires other parts of the system to run, you can’t use a unit test with that external data. The unit test needs to run in isolation. Other system data, such as databases, objects, or network communication, might be required for the code’s functionality. If that's the case, you should use data stubs instead. It’s easiest to write unit tests for small and logically simple blocks of code.
Unit testing strategies
To create unit tests, you can follow some basic techniques to ensure coverage of all test cases.
****Logic checks**
Does the system perform the right calculations and follow the right path through the code given a correct, expected input? Are all paths through the code covered by the given inputs?
****Boundary checks**
For the given inputs, how does the system respond? How does it respond to typical inputs, edge cases, or invalid inputs?
Let’s say you expect an integer input between 3 and 7. How does the system respond when you use a 5 (typical input), a 3 (edge case), or a 9 (invalid input)?
****Error handling**
When there are errors in inputs, how does the system respond? Is the user prompted for another input? Does the software crash?
****Object-oriented checks**
If the state of any persistent objects is changed by running the code, is the object updated correctly?
Unit test example
Here is an example of a very basic method in Python and some test cases with corresponding unit test code.
****Python method**
def add_two_numbers(x, y):
return x + y
****Corresponding unit tests**
def test_add_positives():
result = add_two_numbers(5, 40)
assert result == 45
def test_add_negatives():
result = add_two_numbers(-4, -50)
assert result == -54
def test_add_mixed():
result = add_two_numbers(5, -5)
assert result == 0