class Employee:
address = models.ForeignKey(Address)
def setZipCode(self, zipcode):
setattr(self, 'zipCode', zipcode)
def set_address_property(self, target_property, value):
try:
setattr(self.address, target_property, value)
self.address.save()
except ObjectDoesNotExist:
# TODO. Figure out what to do here
print 'Cannot save'
return
def get_address_property(self, target_property, default):
try:
return getattr(self.address, target_property)
except ObjectDoesNotExist:
return default
@property
def zipCode(self):
return self.get_address_property('zipCode', None)
@zipCode.setter
def zipCode(self, value):
self.set_address_property('zipCode', value)
def functionToTest(employee):
# Blah Blah Blah...
employee.setZipCode(123)
def testFunctionToTest(self):
employee = MagicMock()
employee.address.zipCode = None
employee.attribute.setZipCode = lambda x, y: setattr(x.address, 'zipCode', y)
functionToTest(employee)
self.assertEquals(employee.address.zipCode, 123)
如果我尝试运行此测试,我仍然会将employee.address.zipCode
设为None
而不是123.如何解决此问题?
答案 0 :(得分:3)
您无需测试该属性是否实际设置;你的测试应该只涵盖方法是否被调用:
employee = MagicMock(spec= Employee)
functionToTest(employee)
employee.assert_called_once_with(123)
测试employee.setZipCode()
是否正常工作是单元测试Employee
类的主题,不在测试fuctionToTest()
函数的范围内。