示例
每次使用mock都记不住,今天也是这样,但是这里出现了不一样的地方,先举个例子:
1 | from mock import Mock, patch |
where to patch
上述看也没什么问题,但是此处讲一个Where to patch
的问题.
简单描述:
1 | a.py |
如上,a.py定义了一个SomeClass,然后b.py引入这个Class,然后在某个地方进行实例化此类,ok,如果要patch SomeClass这个类,要从a.py进行patch呢还是从b.py进行patch呢?
例如:
1 |
|
1 |
|
上述哪一种方法才能被正常mock??
引用外文的描述:
1 | Now we want to test some_function but we want to mock out SomeClass using patch. The problem is that when we import module b, which we will have to do then it imports SomeClass from module a. If we use patch to mock out a.SomeClass then it will have no effect on our test; module b already has a reference to the real SomeClass and it looks like our patching had no effect. |
翻译成中文(翻译不好-_-!)
1 |
|
常见的一些mock
- mock class staticmethod
1 |
|
- 如何mock一个异常
1 | with patch( |
- mock class method
1 |
|