我正在测试一个从一个辅助对象获取骨架对象的函数,使用第二个辅助对象修改它,并将修改后的对象传递回第一个帮助器。有点像:
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对象?
答案 0 :(得分:0)
也许不是最好的解决方案,但你可以尝试使用一个模拟,你给你的测试对象两次。然后,您可以控制呼叫顺序。
class ReadModifyUpdateTest(mox.MoxTestBase):
def test_modify(self):
mock_record = self.mox.CreateMockAnthing()
mock_storeModifier = self.mox.CreateMockAnything()
mock_storeModifier.read("test_key").AndReturn(mock_record)
mock_storeModifier.modify(mock_record)
mock_storeModifier.update("test_key", mock_record)
self.mox.ReplayAll()
updater = ReadModifyUpdate(mock_storeModifier, mock_storeModifier)
updater.modify("test_key")
答案 1 :(得分:0)
为我自己的问题提供答案 - 我目前使用副作用来检查通话顺序。
定义帮助程序类:
class OrderedCallSequence(object):
def __init__(self, test_case):
self._expectation_count = 0
self._evaluated = 0
self._test_case = test_case
def assertOrder(self):
self._expectation_count += 1
expected_position = self._expectation_count
def side_effect(*args, **kwargs):
self._evaluated += 1
self._test_case.assertEquals(self._evaluated, expected_position,
msg="Invoked in incorrect sequence")
return side_effect
......测试用例变为:
class ReadModifyUpdateTest(mox.MoxTestBase):
def test_modify(self):
mock_record = self.mox.CreateMockAnthing()
mock_store = self.mox.CreateMockAnything()
mock_modifier = self.mox.CreateMockAnything()
sequence = OrderedCallSequence(self)
mock_store.read("test_key").WithSideEffects(sequence.assertOrder()).AndReturn(mock_record)
mock_modifier.modify(mock_record).WithSideEffects(sequence.assertOrder())
mock_store.update("test_key", mock_record).WithSideEffects(sequence.assertOrder())
self.mox.ReplayAll()
updater = ReadModifyUpdate(mock_store, mock_modifier)
updater.modify("test_key")