简体   繁体   English

Python单元测试-模拟类属性

[英]Python unit test - Mocking a class property

I'm coming from a java background and new to python. 我来自Java背景并且是python的新手。 In Java, if a class initializes its own property like (this is bad for unit testing): 在Java中,如果类像这样初始化其自己的属性(这对单元测试不利):

class TestMe {
    Logger logger;
    public TestMe() {
        this.logger = new Logger();
    }

    //...stuff
}

I'd refactor it so I can provide a mocked dependency and test the class without creating a real instance of Logger: 我将对其进行重构,以便可以提供模拟的依赖关系并测试类,而无需创建Logger的真实实例:

class TestMe {
    Logger logger;
    public TestMe(ILogger logger) {
        this.logger = logger;
    }

    //...stuff
}

But python is a very different language and there may be a way to mock that property without refactoring: 但是python是一种非常不同的语言,可能有一种无需重构即可模拟该属性的方法:

import Logger

class TestMe:
    def __init__(self):
        self.logger = Logger()

    # stuff

is there a way to mock Logger in above python class without a refactor? 有没有一种方法可以在上面的python类中模拟Logger而无需重构?

Yes, there is. 就在这里。 You can just reassign the logger member variable to be whatever you want. 您只需将logger成员变量重新分配为您想要的任何变量即可。 Note that there is no concept of private and public in Python, so you can do this. 请注意,Python中没有私有和公共的概念,因此您可以执行此操作。

In particular, you could assign it to be a Mock or MagicMock object, which are special objects that you can do some introspection on (like making sure self.logger was called/used in some particular fashion), as well as a clean way to do "faking" (you don't have to implement Logger s interface to use them) 特别是,您可以将其分配为MockMagicMock对象,这是可以对其进行自省的特殊对象(例如确保以某种特定方式调用/使用了self.logger ),以及一种干净的方法。进行“伪造”(您无需实现Logger的接口即可使用它们)

from unittest.mock import MagicMock
t = TestMe()
t.logger = MagicMock()
# run some tests that use t (and maybe the Logger)

You can read more about mocking in Python here . 您可以在这里阅读更多有关Python中的模拟的信息

HTH. HTH。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM