【发布时间】:2009-02-14 19:50:07
【问题描述】:
我已经定义了一个自定义错误,但是如果我测试自定义错误是否得到 提出,它失败了。
我的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 是否被提升
【问题讨论】:
-
如果您将 from X import Y 与其他“import X”格式混合使用,这可能会导致您的异常处理无法正常工作。请参阅docs.python.org/2/howto/… 还要小心模块 reload()
标签: django unit-testing