当单元测试类一应该只针对其合作者的公共接口进行测试。在大多数情况下,这很容易实现用假对象替换协作者- 模拟。当正确使用依赖注入时,大多数时候这应该很容易。
但是,当尝试测试工厂类时,事情变得复杂了。让我们看看例子
模块wheel
class Wheel:
"""Cars wheel"""
def __init__(self, radius):
"""Create wheel with given radius"""
self._radius = radius #This is private property
模块engine
class Engine:
"""Cars engine"""
def __init(self, power):
"""Create engine with power in kWh"""
self._power = power #This is private property
模块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
现在让我们有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)
现在我想为CarFactory
. 我想测试一下,工厂正确地创建了对象。但是,我不应该测试对象的私有属性,因为它们将来可能会被更改,这会破坏我的测试。想象一下,Wheel._radius
被替换Wheel._diameter
或被Engine._power
替换Engine._horsepower
。
那么如何测试工厂呢?