注入python class进行测试,不修改class

Inject into python class for testing, without modifying the class

我的任务是为我们的生产管道创建单元测试代码,而不修改生产管道。管道具有写入和读取队列的方法。我正在使用模拟来覆盖这些调用以创建单个 "unit" 测试。但我坚持最后一部分。

我需要访问在管道中创建的对象,但创建它的方法没有 return 对象。将对象设置为 self 以便它在方法 returns.

之后保留在内存中也是不可接受的

我们想知道是否有一种方法可以在 class 方法处于 运行 时注入它,以便我可以在方法 return 之前检索生产对象。

我在下面创建了一个虚拟示例,但方法是相同的。如果您有任何疑问或者我没有很好地解释这一点,请告诉我。谢谢

class production(object):
    def __init__(self):
        self.object_b = 'Test Object'

    def run(self):
        "Other lines of code"
        object_a = self.create_production_object()
        "Other lines of code"
        "Test object here"
        return 0




    def create_production_object(self):
        return 'Production Object'

test_prod_class = production()
test_prod_class.run()
assert(test_prod_class.object_a, 'Production Object')

如何覆盖创建对象的方法,以便它也将对象存储在 self 中?

class MockProduction(production):

    def create_production_object(self):
        self.object_a = super(MockProduction, self).create_production_object()
        return self.object_a