加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

如何在python中为变量赋值编写unittest?

发布时间:2020-12-20 11:55:17 所属栏目:Python 来源:网络整理
导读:这是在 Python 2.7中.我有一个名为A类的类,有些属性我想在用户设置时抛出异常: myA = A()myA.myattribute = 9 # this should throw an error 我想编写一个unittest来确保这会引发错误. 在创建测试类并继承unittest.TestCase之后,我尝试编写如下测试: myA =
这是在 Python 2.7中.我有一个名为A类的类,有些属性我想在用户设置时抛出异常:

myA = A()
myA.myattribute = 9   # this should throw an error

我想编写一个unittest来确保这会引发错误.

在创建测试类并继承unittest.TestCase之后,我尝试编写如下测试:

myA = A()
self.assertRaises(AttributeError,eval('myA.myattribute = 9'))

但是,这会引发语法错误.但是,如果我尝试使用eval(‘myA.myattribute = 9’),它会抛出属性错误.

如何编写单元测试来正确测试?

谢谢.

解决方法

您还可以使用assertRaises作为上下文管理器:

with self.assertRaises(AttributeError):
    myA.myattribute = 9

documentation shows more examples for this if you are interested. assertRaises的文档也有关于这个主题的更多细节.

从该文件:

If only the exception and possibly the msg arguments are given,return a context manager so that the code under test can be written
inline rather than as a function:

06001

这正是你想要做的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读