如何模拟在python中写入同一对象的对象的函数?

时间:2015-08-05 09:58:29

标签: python unit-testing mocking python-unittest

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.如何解决此问题?

1 个答案:

答案 0 :(得分:3)

您无需测试该属性是否实际设置;你的测试应该只涵盖方法是否被调用:

employee = MagicMock(spec= Employee)
functionToTest(employee)
employee.assert_called_once_with(123)

测试employee.setZipCode()是否正常工作是单元测试Employee类的主题,不在测试fuctionToTest()函数的范围内。