Back to Repositories

Testing Abstract Factory Pattern Implementation in python-patterns

This test suite validates the Abstract Factory pattern implementation in a PetShop context, specifically testing the Dog class instantiation and behavior. The tests ensure proper object creation and method invocation through mocking.

Test Coverage Overview

The test coverage focuses on verifying the PetShop class’s ability to create and manage Dog instances through the Abstract Factory pattern. Key functionality tested includes:

  • Dog instance creation through PetShop factory
  • Verification of speak() method invocation
  • Mock object implementation for behavior validation

Implementation Analysis

The testing approach utilizes unittest’s mock functionality to isolate the Dog.speak() method for verification. The implementation demonstrates the Abstract Factory pattern by testing the factory’s ability to create concrete pet instances.

Pattern specifics include:
  • Factory method validation through PetShop class
  • Mock object pattern for method call verification
  • Instance type checking and behavior validation

Technical Details

Testing tools and configuration:

  • unittest framework for test structure
  • unittest.mock.patch for method mocking
  • TestCase class inheritance for assertion methods
  • Mock object call_count tracking

Best Practices Demonstrated

The test suite exemplifies several testing best practices in Python unit testing. Notable practices include:

  • Isolation of dependencies through mocking
  • Clear test method naming conventions
  • Single responsibility principle in test methods
  • Proper use of context managers for mock objects

faif/python-patterns

tests/creational/test_abstract_factory.py

            
import unittest
from unittest.mock import patch

from patterns.creational.abstract_factory import Dog, PetShop


class TestPetShop(unittest.TestCase):
    def test_dog_pet_shop_shall_show_dog_instance(self):
        dog_pet_shop = PetShop(Dog)
        with patch.object(Dog, "speak") as mock_Dog_speak:
            pet = dog_pet_shop.buy_pet("")
            pet.speak()
            self.assertEqual(mock_Dog_speak.call_count, 1)