This content originally appeared on DEV Community and was authored by DevOps Fundamental
Understanding Best Way to Unit Testing for Beginners
Hey there! So you’re starting to hear about “unit testing” and wondering what all the fuss is about? Don’t worry, it sounds scarier than it is. In fact, learning to write good unit tests is one of the best things you can do as a new programmer. It’ll save you headaches down the road, make your code more reliable, and even impress interviewers! Many companies ask about testing in junior developer interviews, so getting a grasp on the basics is a great investment.
2. Understanding “best way to unit testing”
Imagine you’re building with LEGOs. You wouldn’t just dump all the bricks out and hope for the best, right? You’d build small sections first – maybe a wall, then a tower, then connect them. Unit testing is similar!
Instead of testing your entire program at once (which can be super complicated), you test small, individual “units” of code. A “unit” is usually a single function or method.
Think of a function like a mini-program within your bigger program. It takes some input, does something with it, and gives you an output. Unit testing is about making sure that mini-program always does what you expect it to, given specific inputs.
Why is this helpful? Because if a small part of your code is broken, unit tests will tell you exactly where the problem is. It’s much easier to fix a small piece than to debug a huge, tangled mess!
Here’s a simple way to visualize it:
graph LR
A[Your Program] --> B(Unit 1 - Function A)
A --> C(Unit 2 - Function B)
A --> D(Unit 3 - Function C)
B -- Test --> B_test[Unit 1 Tests]
C -- Test --> C_test[Unit 2 Tests]
D -- Test --> D_test[Unit 3 Tests]
This diagram shows how your program is broken down into smaller units, and each unit has its own set of tests.
3. Basic Code Example
Let’s look at a simple example in Python. We’ll create a function that adds two numbers together.
def add_numbers(x, y):
"""This function adds two numbers together."""
return x + y
Now, let’s write a unit test for this function. We’ll use a testing framework called unittest
which comes with Python.
import unittest
class TestAddNumbers(unittest.TestCase):
def test_add_positive_numbers(self):
self.assertEqual(add_numbers(2, 3), 5)
def test_add_negative_numbers(self):
self.assertEqual(add_numbers(-1, -1), -2)
def test_add_positive_and_negative(self):
self.assertEqual(add_numbers(5, -2), 3)
if __name__ == '__main__':
unittest.main()
Let’s break this down:
-
import unittest
: This line imports theunittest
module. -
class TestAddNumbers(unittest.TestCase)
: This creates a class to hold our tests. It must inherit fromunittest.TestCase
. -
def test_add_positive_numbers(self)
: Each function that starts withtest_
is a test case. The name should clearly describe what you’re testing. -
self.assertEqual(add_numbers(2, 3), 5)
: This is an assertion. It checks if the result ofadd_numbers(2, 3)
is equal to5
. If it is, the test passes. If not, the test fails.unittest
provides many different assertion methods (likeassertEqual
,assertTrue
,assertFalse
, etc.). -
if __name__ == '__main__': unittest.main()
: This line runs the tests when you execute the Python file.
4. Common Mistakes or Misunderstandings
Let’s look at some common mistakes beginners make when writing unit tests:
Incorrect code:
def test_add_numbers():
assert add_numbers(2, 3) == 5
Corrected code:
import unittest
class TestAddNumbers(unittest.TestCase):
def test_add_numbers(self):
self.assertEqual(add_numbers(2, 3), 5)
Explanation: You need to define your tests within a class that inherits from unittest.TestCase
. Using self.assertEqual
is the correct way to make an assertion within a unittest
test case.
Incorrect code:
def test_add_numbers(self):
add_numbers(2, 3) # No assertion!
Corrected code:
import unittest
class TestAddNumbers(unittest.TestCase):
def test_add_numbers(self):
self.assertEqual(add_numbers(2, 3), 5)
Explanation: Simply calling the function isn’t enough. You need to assert that the result is what you expect. Without an assertion, the test will always pass, even if the function is broken!
Incorrect code:
import unittest
class TestAddNumbers(unittest.TestCase):
def test_add_numbers(self):
self.assertEqual(add_numbers(2, 3), 6) # Wrong expected value!
Corrected code:
import unittest
class TestAddNumbers(unittest.TestCase):
def test_add_numbers(self):
self.assertEqual(add_numbers(2, 3), 5)
Explanation: Make sure your expected value in the assertion is correct! Double-check your calculations and logic.
5. Real-World Use Case
Let’s imagine you’re building a simple calculator. You might have classes for Calculator
and Operation
(like Addition
, Subtraction
, etc.).
class Calculator:
def __init__(self):
pass
def add(self, x, y):
return x + y
def subtract(self, x, y):
return x - y
You would then write unit tests for the Calculator
class, specifically for the add
and subtract
methods. These tests would verify that the calculator performs the correct operations for various inputs (positive numbers, negative numbers, zero, etc.). This ensures that the core logic of your calculator is working correctly before you add more complex features like a user interface.
6. Practice Ideas
Here are a few ideas to practice your unit testing skills:
- String Reverser: Write a function that reverses a string. Then, write unit tests to verify it works correctly for different strings (empty string, palindrome, regular string).
- Simple Interest Calculator: Create a function that calculates simple interest. Write tests to cover different principal amounts, interest rates, and time periods.
- List Filter: Write a function that filters a list of numbers to return only the even numbers. Write tests to ensure it handles empty lists and lists with no even numbers correctly.
- Password Validator: Write a function that checks if a password meets certain criteria (e.g., minimum length, contains a number, contains a special character). Write tests to cover valid and invalid passwords.
- Temperature Converter: Write functions to convert between Celsius and Fahrenheit. Write tests to verify the conversions are accurate.
7. Summary
You’ve now learned the basics of unit testing! We covered what unit testing is, why it’s important, how to write simple tests using unittest
in Python, and some common mistakes to avoid.
Remember, unit testing is a skill that improves with practice. Don’t be afraid to experiment, make mistakes, and learn from them.
Next steps? Explore more advanced testing concepts like mocking, test-driven development (TDD), and different testing frameworks. Keep building, keep testing, and keep learning! You’ve got this!
This content originally appeared on DEV Community and was authored by DevOps Fundamental