单元测试之Monkey Patch

发表于:2014-3-28 11:51

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:juvxiao    来源:51Testing软件测试网采编

  再说monkey patch之前先说下, python中的Test Double, Test Double就是在测试case中给某个对象做替身的意思. 用一个假对象替换.
  用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的名空间。达到测试时的狸猫换太子。
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号