gpt4 book ai didi

Django unittest assertRaise自定义错误

转载 作者:行者123 更新时间:2023-12-04 18:17:32 28 4
gpt4 key购买 nike

我已经定义了一个自定义错误,但是如果我测试是否得到了自定义错误
提出来,它失败了。

我的models.py:

class CustomError(Exception):
"""
This exception is my custom error
"""

class Company(models.Model):
name = models.CharField(max_length=200)

def test_error(self):
raise CustomError('hello')

在我的tests.py中:
import unittest
from myapp.models import Company,Customer,Employee,Location,Product,ProductCategory,AllreadyPayedError,CustomError

class CompanyTestCase(unittest.TestCase):
def setUp(self):
self.company = Company.objects.create(name="lizto")

def test2(self):
self.assertRaises(CustomError, self.company.test_error)

测试失败,显示以下输出:
======================================================================
ERROR: test2 (myapp.api.tests.CompanyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/......./tests.py", line 27, in test2
self.assertRaises(CustomError, self.company.test_error)
File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/unittest.py", line 320, in failUnlessRaises
callableObj(*args, **kwargs)
File " /Users/....../models.py", line 17, in test_error
raise CustomError('hello')
CustomError: hello

----------------------------------------------------------------------
Ran 18 tests in 1.122s

任何人都知道如果提高 CustomError我应该怎么做才能测试

最佳答案

您可以捕获该错误并断言它已发生。

例如:(未测试)

def test2(self)
error_occured = False
try:
self.company.test_error()
except CustomError:
error_occured = True

self.assertTrue(error_ocurred)

似乎远非理想,但会解开您的障碍。

关于Django unittest assertRaise自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/549677/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com