简体   繁体   English

模拟类中的类实例

[英]Mocking class instances inside a Class

I'm currently writing tests for a wsgi server I made. 我正在为我制作的wsgi服务器编写测试。 The server class at __init__ constructor inits 2 instances of other classes as members. __init__构造函数中的服务器类将其他类的2个实例作为成员。 Lets say 让我们说

def __init__(self):
  self.a = A()
  self.b = B()

During tests, how can I mock self.a and and self.b as mock classes I made for them instead of using A and B ? 在测试期间,我如何模拟self.a和self.b作为我为他们制作的模拟类而不是使用A和B?

#I use this if I want to mock the entire server class
@mock.patch('myproject.server.MyServerClass',autospec=True)

The more python I write the more curious I am about situations like this. 我写的python越多,我对这种情况就越好奇。 My inclination is usually to introduce dependency injection and pass in the created A and B classes on the constructor. 我倾向于引入依赖注入并在构造函数中传入创建的A和B类。 This makes it easy to both see the external dependencies and change them up when i need. 这样可以很容易地看到外部依赖关系并在需要时更改它们。 But sometimes that is overkill. 但有时这太过分了。 Could you not just: 你不能只是:

server = Server()
server.a = MockA()
server.b = MockB()

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

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