135

我正在尝试创建一个 UnitTest 来验证一个对象是否已被删除。

from django.utils import unittest
def test_z_Kallie_can_delete_discussion_response(self):
  ...snip...
  self._driver.get("http://localhost:8000/questions/3/want-a-discussion") 
  self.assertRaises(Answer.DoesNotExist, Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>'))

我不断收到错误:

DoesNotExist: Answer matching query does not exist.
4

6 回答 6

201

如果您想要一种通用的、独立于模型的方式来捕获异常,您也可以 import ObjectDoesNotExistfrom django.core.exceptions

from django.core.exceptions import ObjectDoesNotExist

try:
    SomeModel.objects.get(pk=1)
except ObjectDoesNotExist:
    print 'Does Not Exist!'
于 2012-06-19T21:26:30.260 回答
147

您不需要导入它 - 正如您已经正确编写的那样DoesNotExist,在这种情况下,它是模型本身的属性Answer

您的问题是您在将get方法传递给assertRaises. 您需要将参数与可调用对象分开,如unittest 文档中所述:

self.assertRaises(Answer.DoesNotExist, Answer.objects.get, body__exact='<p>User can reply to discussion.</p>')

或更好:

with self.assertRaises(Answer.DoesNotExist):
    Answer.objects.get(body__exact='<p>User can reply to discussion.</p>')
于 2012-06-19T21:28:56.420 回答
12

DoesNotExist始终是模型不存在的属性。在这种情况下,它会是Answer.DoesNotExist

于 2012-06-19T21:19:42.270 回答
3

需要注意的一件事是,第二个参数assertRaises 必须是可调用的 - 而不仅仅是属性。例如,我对这个陈述有困难:

self.assertRaises(AP.DoesNotExist, self.fma.ap)

但这很好用:

self.assertRaises(AP.DoesNotExist, lambda: self.fma.ap)
于 2013-03-18T04:59:18.847 回答
3
self.assertFalse(Answer.objects.filter(body__exact='<p>User...discussion.</p>').exists())
于 2016-01-28T09:19:01.097 回答
0

这就是我进行此类测试的方式。

from foo.models import Answer

def test_z_Kallie_can_delete_discussion_response(self):

  ...snip...

  self._driver.get("http://localhost:8000/questions/3/want-a-discussion") 
  try:
      answer = Answer.objects.get(body__exact = '<p>User can reply to discussion.</p>'))      
      self.fail("Should not have reached here! Expected no Answer object. Found %s" % answer
  except Answer.DoesNotExist:
      pass # all is as expected
于 2012-06-19T21:28:33.157 回答