现在来制造一些异常情况!
首先,声明一个异常。
class ZooException(Exception):
pass
def test_feed(self):
zookeeper = self.m.CreateMock(zoo.ZooKeeper)
zookeeper.feed(mox.StrContains("penguin"))
zookeeper.feed(mox.StrContains("swan")).AndRaise(zoo.ZooException)
z = zoo.Zoo(zookeeper)
self.m.ReplayAll()
with self.assertRaises(zoo.ZooException):
z.feed()
self.m.VerifyAll()
现在将类zookeeper设定的再复杂一点,让它也包含一些自己的内部变量。类似于设定饲养员是被雇佣于一家Vendor。
class ZooKeeper(object):
def __init__(self, name):
self.name = name
self.vendor = Vendor()
def feed(self, animal):
print "feed animal %s" % animal
class Vendor(object):
def get_name(self):
return "Elet Cop, Ltd."
def get_zookeeper_vendor(self):
name = "Vendor:%s" % self.zookeeper.vendor.get_name()
return name
测试用例如下:
def test_get_zookeeper_vendor(self):
zookeeper = self.m.CreateMock(zoo.ZooKeeper)
z = zoo.Zoo(zookeeper)
self.m.ReplayAll()
self.assertEqual("Vendor:Elet Cop, Ltd.", z.get_zookeeper_vendor())
self.m.VerifyAll()
UnknownMethodCallError: Method called is not a member of the object: vendor
def test_get_zookeeper_vendor(self):
zookeeper = self.m.CreateMock(zoo.ZooKeeper)
vendor = self.m.CreateMock(zoo.Vendor)
vendor.get_name().AndReturn("Test Cop, Ltd.")
zookeeper.vendor = vendor
z = zoo.Zoo(zookeeper)
self.m.ReplayAll()
self.assertEqual("Vendor:Test Cop, Ltd.", z.get_zookeeper_vendor())
self.m.VerifyAll()