Labs ICT
โญ Pro Login

Test Methods & Naming

Writing test methods and following naming conventions

Test Methods & Naming

Test methods are the individual functions that contain your test logic. Following proper naming conventions ensures that unittest can discover and run your tests automatically.

Naming Conventions

import unittest

class TestCalculator(unittest.TestCase):
    # This IS discovered as a test
    def test_add_positive_numbers(self):
        self.assertEqual(2 + 3, 5)

    # This IS discovered as a test
    def test_add_negative_numbers(self):
        self.assertEqual(-1 + -1, -2)

    # This is NOT discovered (doesn't start with test_)
    def helper_add(self, a, b):
        return a + b

    # This is NOT discovered (doesn't start with test_)
    def check_result(self):
        pass

Test Methods with setUp

import unittest

class TestDatabase(unittest.TestCase):
    def setUp(self):
        self.connection = create_connection()

    def test_query_user(self):
        result = self.connection.query("SELECT * FROM users")
        self.assertIsNotNone(result)

    def test_insert_user(self):
        result = self.connection.insert("users", {"name": "Bob"})
        self.assertTrue(result)

Descriptive Test Names

Write test names that describe the expected behavior:

# Good: describes what is being tested and expected outcome
def test_login_with_valid_credentials_returns_true(self):
    ...

def test_login_with_invalid_password_raises_error(self):
    ...

def test_empty_cart_shows_zero_total(self):
    ...

Key Takeaway

All test methods must start with test_ and take self as the only parameter. Use descriptive names that clearly state what the test verifies.

๐Ÿงช Quick Quiz

What prefix should test methods start with?