我已经定义了一个自定义错误但是如果我测试是否有自定义错误 提出,它失败了。
我的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
是否被提升
答案 0 :(得分:4)
您可以捕获错误并声明它已发生。
例如:(未经测试)
def test2(self)
error_occured = False
try:
self.company.test_error()
except CustomError:
error_occured = True
self.assertTrue(error_ocurred)
似乎远非理想,但会阻止你。
答案 1 :(得分:2)
感谢Andy的回答然而问题是我使用了错误/不同类型的导入: 在我的INSTALLED_APPS设置中,我有myproj.myapp
我改变之后:
from myapp.models import Company,CustomError
要:
from myproj.myapp.models import Company,CustomError
按预期工作
答案 2 :(得分:1)
Assert Raises似乎比其他单元测试更不直观。我认为这篇文章给出了如何使用它的非常好的图片(不仅提供了解决方法): Why isn't assertRaises catching my Attribute Error using python unittest?
干杯!