使用 Mox 和 Python 测试模拟对象之间的调用顺序
我正在测试一个函数,该函数从一个帮助器对象获取骨架对象,使用第二个帮助器对其进行修改,然后将修改后的对象传递回第一个帮助器。大致如下:
class ReadModifyUpdate(object):
def __init__(self, store, modifier):
self._store = store
self._modifier = modifier
def modify(key):
record = self._store.read(key)
self._modifier.modify(record)
self._store.update(key, record)
使用Python和Mox,我们可以用以下方法进行测试:
class ReadModifyUpdateTest(mox.MoxTestBase):
def test_modify(self):
mock_record = self.mox.CreateMockAnthing()
mock_store = self.mox.CreateMockAnything()
mock_modifier = self.mox.CreateMockAnything()
mock_store.read("test_key").AndReturn(mock_record)
mock_modifier.modify(mock_record)
mock_store.update("test_key", mock_record)
self.mox.ReplayAll()
updater = ReadModifyUpdate(mock_store, mock_modifier)
updater.modify("test_key")
...但这并没有捕获在modifier.modify()之前无意中调用store.update()的错误。在 Mox 中,有没有一种好方法来检查多个模拟上调用的方法的顺序?像 EasyMock 的 MocksControl 对象之类的东西?
I'm testing a function that obtains a skeleton object from one helper object, modifies it using a second helper, and passes the modified object back to the first helper. Something along the lines of:
class ReadModifyUpdate(object):
def __init__(self, store, modifier):
self._store = store
self._modifier = modifier
def modify(key):
record = self._store.read(key)
self._modifier.modify(record)
self._store.update(key, record)
Using Python and Mox, we can test this with:
class ReadModifyUpdateTest(mox.MoxTestBase):
def test_modify(self):
mock_record = self.mox.CreateMockAnthing()
mock_store = self.mox.CreateMockAnything()
mock_modifier = self.mox.CreateMockAnything()
mock_store.read("test_key").AndReturn(mock_record)
mock_modifier.modify(mock_record)
mock_store.update("test_key", mock_record)
self.mox.ReplayAll()
updater = ReadModifyUpdate(mock_store, mock_modifier)
updater.modify("test_key")
...but this doesn't catch the bug in which store.update() is inadvertently called before modifier.modify(). Is there a good way, in Mox, to check the order of methods called on multiple mocks? Something like EasyMock's MocksControl object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许不是最好的解决方案,但您可以尝试使用一个模拟,为被测对象提供两次模拟。然后您就可以控制呼叫顺序。
Maybe not the best solution but you could try to use one mock that you give twice to your object under test. You then have control over the call order.
为了回答我自己的问题 - 我目前已经使用检查调用顺序的副作用来完成这项工作。
定义一个辅助类:
...测试用例变为:
To provide an answer to my own question - I've currently got this working using a side effect which checks the call order.
Defining a helper class:
...the test case becomes: