【发布时间】:2015-03-20 13:18:56
【问题描述】:
我有自己的类 Article 旨在与 PostgreSQL 一起工作。从该类创建的每个对象都用于处理一行。现在我不知道如何测试异常情况。当我创建这样的案例时:
article = Article(2)/*connects to the db and loads line with id 2*/
print article.title2 /*here my db does not have table title2 and should launch an error*/
它应该抛出错误。它确实) 测试用例应该是什么样子?我使用单元测试。我的测试类使用了我的错误方法但不起作用:
import unittest
from article import * /*import my ORM class*/
class EntityTest(unittest.TestCase):
def setUp(self):
Entity.db = psycopg2.connect("dbname='postgres' user='postgres' host='192.168.136.129' password='xxxxxxxxx'")/*creates connection to db*/
def test_should_lounch_attr_error(self):
article = Article(2)
print article.title2
self.assertRaisesRegex(article.AttributeError, "No attribute exists")
我没有如何创建测试用例的经验,也没有太多关于如何创建测试用例的好文档((( 如果测试用例通过(生成异常),我不明白,unittest 应该返回 Ok 语句。现在它只是显示错误。
【问题讨论】:
-
它显示错误,因为它是在您的断言语句之前引发的,在
print article.title2行。 assertRaisesRegexp 用法示例:docs.python.org/2/library/… -
这个文档是我检查的第一个文档)我尝试更改为 self.assertRaisesRegexp(article.AttributeError, "No attribute exists", article.atribute)。同样的结果
标签: python postgresql unit-testing exception