單元測試之Monkey Patch
用Test Double時, 可以有三種實現的形式, Stub,Mock object, Fake Object, Mock object 在我的另一博文中http://blog.csdn.net/juvxiao/article/details/21562325分析了下, 其他兩種比較簡單, 可看https://wiki.openstack.org/wiki/SmallTestingGuide了解 ,這個link中還提到Test Double的兩種實現方式: 依賴注入 和 monkey patching.
依賴注入
class FamilyTree(object): def __init__(self, person_gateway): self._person_gateway = person_gateway |
可以把person_gateway用一個假對象替換, 從而讓測試專注在FamilyTree本身,
person_gateway = FakePersonGateway() # ... tree = FamilyTree(person_gateway) monkey patching |
這種測試只能運行在像python這樣的動態語言中, 它通過在運行時替換名空間的方式實現測試。如下例
class FamilyTree(object): def __init__(self): self._person_gateway = mylibrary.dataaccess.PersonGateway() |
那我們就可以在測試時把mylibrary.dataaccess.PersonGateway名空間替換為FakeGataway名空間.
mylibrary.dataaccess.PersonGateway = FakePersonGateway # ... tree = FamilyTree() 通過一個OpenStack中使用monkey patch的例子來說說, 這個代碼片斷摘自nova的單元測試test_virt_driver.py,用于講述monkey patch用法 import nova.tests.virt.libvirt.fake_imagebackend as fake_imagebackend import nova.tests.virt.libvirt.fake_libvirt_utils as fake_libvirt_utils import nova.tests.virt.libvirt.fakelibvirt as fakelibvirt sys.modules['libvirt'] = fakelibvirt import nova.virt.libvirt.driver import nova.virt.libvirt.firewall self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.imagebackend', fake_imagebackend)) self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.libvirt', fakelibvirt)) self.useFixture(fixtures.MonkeyPatch( 'nova.virt.libvirt.driver.libvirt_utils', fake_libvirt_utils)) |
這個例子中使用了fixtures module(fixtures就是一個testcase助手, 把一些不依賴具體測試的過程提取出來放到fixtures module中, 可以使得測試代碼干凈)來實現monkey patch, 就是用前幾行的fake object 這個名空間替換真正driver object的名空間。達到測試時的貍貓換太子。