Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8474567
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T17:39:42+00:00 2026-06-10T17:39:42+00:00

When unit testing class one should test only against public interface of its collaborators.

  • 0

When unit testing class one should test only against public interface of its collaborators. In most cases, this is easily achieved replacing collaborators with fake objects – Mocks. When using dependency injection properly, this should be easy most times.

However, things get complicated when trying to test factory class. Let us see example

Module wheel

class Wheel:
    """Cars wheel"""

     def __init__(self, radius):
         """Create wheel with given radius"""

         self._radius = radius #This is private property

Module engine

 class Engine:
     """Cars engine"""

     def __init(self, power):
     """Create engine with power in kWh"""

         self._power = power #This is private property

Module car

class Car:
    """Car with four wheels and one engine"""

    def __init__(self, engine, wheels):
        """Create car with given engine and list of wheels"""

        self._engine = engine
        self._wheels = wheels

Now let us have CarFactory

from wheel import Wheel
from engine import Engine
from car import Car

class CarFactory:
    """Factory that creates wheels, engine and put them into car"""

    def create_car():
        """Creates new car"""

        wheels = [Wheel(50), Wheel(50), Wheel(60), Wheel(60)]
        engine = Engine(500)
        return Car(engine, wheels)

Now I want to write an unit test for the CarFactory. I want to test, the factory creates objects correctly. However, I should not test the private properties of objects, because they can be changed in future and that would break my tests. Imagine, Wheel._radius replaced by Wheel._diameter or Engine._power replaced by Engine._horsepower.

So how to test the factory?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T17:39:43+00:00Added an answer on June 10, 2026 at 5:39 pm

    Fortunately in python testing factories is easy thanks to monkey_patching. You can replace not only instances of objects, but also whole classes. Let us see example

    import unittest
    import carfactory
    from mock import Mock
    
    def constructorMock(name):
        """Create fake constructor that returns Mock object when invoked"""
        instance = Mock()
        instance._name_of_parent_class = name
        constructor = Mock(return_value=instance)
        return constructor
    
    class CarFactoryTest(unittest.TestCase):
    
        def setUp():
            """Replace classes Wheel, Engine and Car with mock objects"""
    
            carfactory.Wheel = constructorMock("Wheel")
            carfactory.Engine = constructorMock("Engine")
            carfactory.Car = constructorMock("Car")
    
        def test_factory_creates_car():
            """Create car and check it has correct properties"""
    
            factory = carfactory.CarFactory()
            car_created = factory.create_car()
    
            # Check the wheels are created with correct radii
            carfactory.Wheel.assert_called_with(radius=50)
            carfactory.Wheel.assert_called_with(radius=50)
            carfactory.Wheel.assert_called_with(radius=60)
            carfactory.Wheel.assert_called_with(radius=60)
    
            # Check the engine is created with correct power
            carfactory.Engine.assert_called_once_with(power=500)
    
            # Check the car is created with correct engine and wheels
            wheel = carfactory.Wheel.return_value
            engine = carfactory.Engine.return_value
            carfactory.Car.assert_called_once_with(engine, [wheel, wheel, wheel, wheel])
    
            # Check the returned value is the car created
            self.assertEqual(car_created._name_of_parent_class, "Car")
    

    So we replace the classes and their constructors with Mock, that returns our fake instance. That enable us to check, the constructor was called with correct parametres and so we do not need to rely on real classes. We are really able in python to use not only fake instances, but also fake classes.

    Also, I have to mention, the code above is not ideal one. For example, fake constructor should really create new Mock for each request, so we can check the car is called with correct wheels (correct order for example). This could be done, but the code would be longer and I wanted to keep the example as simple as possible.

    In the example I have used Mock library for python http://www.voidspace.org.uk/python/mock/

    But it is not necessary.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Should one create unit tests involving IO? Ie, testing a class method for serializing/deserializing
I want to create a unit test for integration testing. What class should I
I am writing some unit test and I have a unit testing base class
this is one of my questions about unit testing. I'm reading The Art Of
I'm unit testing a class that gets some parameters injected by Autofac. Some of
For unit testing a Scala project, I am writing my own simple javax.sql.DataSource class
I have a question about unit testing. Say I have a controller with one
I'm trying to write a unit test for a class that generates distinct strings.
I'm trying to get my head round Unit Testing and there's one more piece
this is my first step into the world on unit-testing so please be patient.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.