为什么Django单元测试没有看到引发异常?

时间:2018-05-30 14:27:10

标签: django unit-testing django-models

我正在尝试在我的一个模型中测试一个静态方法,但是测试没有看到正在被引发的异常,我不明白为什么。

这是模型和静态方法:

# models.py
class List(models.Model):
    owner = models.ForeignKey(User)
    type = models.ForeignKey('ListType', help_text=_('Type of list'))
    name = models.CharField(_('list'), max_length=128, help_text=_('Name of list'))

class ListType(models.Model):
    type = models.CharField(_('type'), max_length=16)

@staticmethod
def read_list(list_id, list_name, owner, list_type):
    try:
        return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type)
    except List.DoesNotExist:
        return None

以下是测试:

# tests.py
from django.test import TestCase
from .factories import *
from .models import List, ListType

class TestFuncs(TestCase):
    def test_read_list_exc(self):
        with self.assertRaises(List.DoesNotExist):
            uf = UserFactory()
            lt = ListType.objects.get(type='Member')
            lf = ListFactory(owner=uf, type=lt, name='foo')
            # I've created one list but its name isn't 'bar'
            list = List.read_list(999, 'bar', uf, lt)

如果我在read_list方法中设置调试断点并运行测试,我确实看到引发了异常:

# set_trace output:
(<class 'list.models.DoesNotExist'>, DoesNotExist('List matching query does not exist.',))

# test output:
...
File "...."
    list = List.read_list(999, 'bar', uf, lt)
AssertionError: DoesNotExist not raised

我在这里读到了有关如何检测此类异常的其他问题,我认为我做得对。只是为了好玩,我将测试改为以下但是没有解决问题:

        ...
        with self.assertRaises(list.models.DoesNotExist):
        ...

谁能看到我做错了什么?

2 个答案:

答案 0 :(得分:2)

在静态方法中,您捕获异常并返回None

您可以更改测试以使用assertIsNone

l = List.read_list(999, 'bar', uf, lt)  # don't use list as a variable
self.assertIsNone(l)

或者,如果您确实希望该方法引发异常,则删除try..except。

@staticmethod
def read_list(list_id, list_name, owner, list_type):
    return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type)

答案 1 :(得分:0)

您已经在DoesNotExist内处理了read_list异常,因此不会将其抛给测试用例。

要抛出异常,您可以使用raise运算符:

@staticmethod
def read_list(list_id, list_name, owner, list_type):
    try:
        return List.objects.get(pk=list_id, name=list_name, owner=owner, type=list_type)
    except List.DoesNotExist as e:
        some actions to handle exception, for example logging
        ...
        raise e