幸运的是,在python中,由于monkey_补丁,测试工厂很容易。不仅可以替换对象的实例,还可以替换整个类。让我们看看例子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")
所以我们用Mock替换类及其构造函数,这将返回我们的伪实例。这使我们能够检查,构造函数是用正确的参数调用的,因此我们不需要依赖真正的类。在python中,我们不仅可以使用伪实例,还可以使用伪类。在
另外,我必须指出,上面的代码不是理想的。例如,伪构造函数应该为每个请求创建新的Mock,这样我们就可以检查调用的汽车是否使用正确的车轮(例如正确的顺序)。这是可以做到的,但代码会更长,我希望使示例尽可能简单。在
但没有必要。在