[英]Python class mock. How can I get mock-class method calls information
I have a class named Client providing some service by its getResponse method. 我有一个名为Client的类,通过其getResponse方法提供了一些服务。 This class is used by other classes.
此类由其他类别使用。 I make unit testing for class Driver who uses the Client class.
我对使用Client类的Driver类进行单元测试。 By using mock.patch, I replace the Client class by mock class called MockClient which has the same getResponse method returning some predefined values.
通过使用mock.patch,我用名为MockClient的模拟类替换Client类,该类具有返回某些预定义值的相同getResponse方法。 It works great.
效果很好。 But now I want to test parameters the getRsponse method was called with.
但是现在我想测试调用getRsponse方法的参数。 I want to do it by using the *assert_has_calls* method.
我想通过使用* assert_has_calls *方法来做到这一点。 Did not find how to do it.
没找到怎么做。 Please advice.
请指教。
Class under test: 被测课程:
# Driver and its Client
class Driver:
def __init__ (self):
self.client = Client()
def call(self, param):
return self.client.getResponse(param)
class Client:
def getResponse(self, param):
return 'original'
This is the Test class with the mock class: 这是带有模拟类的Test类:
import unittest
import mock
import driver
from driver import Driver
from driver import Client
class MockClient:
def getResponse(self,param):
return 'mock class'
class TestIt(unittest.TestCase):
def setUp(self):
self.mock_client = mock.patch('driver.Client',create=True, new=MockClient)
self.mock_client.start()
def tearDown(self):
self.mock_client.stop()
def test_call(self):
driver = Driver()
result = driver.call('test')
self.assertEqual(result, 'mock class')
assert_has_calls
expects a list of call
objects that it can compare to. assert_has_calls
需要一个可以比较的call
对象列表。 You can get a call
object by calling the mock.call
helper function with your expected arguments and keyword arguments. 您可以通过使用期望的参数和关键字参数调用
mock.call
辅助函数来获得call
对象。
This example is straight from the documentation and illustrates the usage quite well: 该示例直接来自文档,并很好地说明了用法:
mock = Mock(return_value=None)
mock(1)
mock(2)
mock(3)
mock(4)
calls = [call(2), call(3)]
mock.assert_has_calls(calls)
calls = [call(4), call(2), call(3)]
mock.assert_has_calls(calls, any_order=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.