【问题标题】:Inject into python class for testing, without modifying the class注入python类进行测试,无需修改类
【发布时间】:2018-02-06 16:36:17
【问题描述】:

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

我需要访问在管道中创建的对象,但创建它的方法不返回该对象。将对象设置为 self 以便在方法返回后保留在内存中也是不可接受的。

我们想知道是否有一种方法可以在类方法运行时注入它,这样我就可以在方法返回之前检索生产对象。

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

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')

【问题讨论】:

    标签: python unit-testing mocking python-mock


    【解决方案1】:

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

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

    【讨论】:

    • 这对我们来说真的不起作用,因为无论何时修改生产代码,都必须对测试生产代码进行相同的修改。不过还是谢谢。
    • @mobone 没有继承和super(见编辑)。
    • @mobone 请注意,所有其他方法都继承自production,因此无需在子类中更改它们,因为它们在父类中更改。而且由于我现在打电话给父母create_production_object,即使是该方法的更改也会自动传播到测试类。
    • 我能够覆盖我们的“store_production_object”方法来设置 self.谢谢。
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 2013-06-17
    • 2011-01-11
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多