[英]Test django model with foreign key to another model
我想測試一個特定的模型而不必擔心它具有外鍵(FK)的另一個模型。
假設我的模型捆綁包需要其他模型會話的外鍵: models.py
:
class Bundle(ModelCommon):
session = models.ForeignKey(verbose_name=_('Session'), to=Session, default=None, null=False, blank=False)
available = models.BooleanField(verbose_name=_('Available'), default=True, null=False, blank=False)
當我嘗試在test_models.py
上用Mock測試我的Bundle類時(因為我不需要關心Session對象中的字段值):
def setUp(self):
MockSession = mock.create_autospec(Session)
self.test_session = MockSession()
self.bundle = Bundle(session=self.test_session, name='Mega Bundle', enabled=True, available=True, price=0)
def test_event_enabled_is_default_false(self):
session = Session()
self.assertFalse(session.enabled)
我不斷收到此消息:
Error
Traceback (most recent call last):
File "test_models.py", line 181, in setUp
self.bundle = Bundle(session=self.test_session, name='Mega Bundle', enabled=True, available=True, price=0)
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '_state'
問題是:在這種情況下使用測試倍數的絕對正確方法是什么? 因為到目前為止,我還沒有成功使用它。
似乎您正在嘗試模擬Session.__init__
通過autospec在Session.__init__
設置的屬性。 您可以在此相關問題中查看更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.