单元测试第一类应该仅针对其协作者的公共接口进行测试。在大多数情况下,使用虚假物品代替合作伙伴可以轻松实现 - Mocks。正确使用依赖注入时,这应该很容易。如何在Python中对工厂进行单元测试?
但是,当试图测试工厂类时,事情变得复杂。让我们来看看例子
模块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
所取代。
那么如何测试工厂呢?
你为什么写Java并将其称为Python?不需要CarFactory类:'create_car'应该是一个独立的函数。我们在Python中没有私有变量。 –
@丹尼尔罗斯曼当我说私人时,我的意思是私人的内部(而不是api的一部分)。我不是指私人语言结构。而关于CarFactory的课程,你能解释它为什么错了吗?我是新来的python,所以道歉我不pythonic足够。 –
如果不封装任何数据,则不需要创建类。类不是放置函数的简单场所:这就是模块的用途。将'create_car'作为模块级别的独立函数。另外请注意,不需要将'Wheel','Car'和'Engine'放在单独的模块中。 –