我希望在我的测试中模拟其中一个模型的方法。这是我要模拟的方法所在的模型:
class Customer(models.Model):
# Fields ...
def save(self, *args, **kwargs):
update_collector = self.id is None
super(Customer, self).save(*args, **kwargs)
if update_collector:
self.send_to_address_book()
def send_to_address_book(self): # This is the method I want mocked
email = self.user.email
first_name = self.user.first_name
last_name = self.user.last_name
print("This is not being mocked")
investigate_customer.apply_async(
args=[first_name, last_name, email]
)
然后,我希望所有继承自CustomerTestCase
的测试用例都能对send_to_address_book
进行模拟。
class CustomerTestCase(object):
@mock.patch('accounts.models.Customer.send_to_address_book')
def create_user_and_customer(self, name, mock_method):
mock_method.return_value = None
if not name:
name = 'test'
email = name + '@test.si'
user = User.objects.create_user(name, email)
customer = Customer.objects.create(user=user)
return user, customer
然而,当我运行以下测试时,
send_to_address_book
没有被模拟。class CustomerQueriesTest(CustomerTestCase, TestCase):
def setUp(self):
G(Language, code='en', name='English')
self.user, self.customer = self.create_user_and_customer()
def test_queries_running(self):
profile = self.user.profile
resp = self.user.profile.queries_running()
self.assertEqual(resp, 0)
G(Package) # using Django dynamic fixtures to create a new Package
我错过了什么?