Python-测试属性引发异常 [英] Python - test a property throws exception

查看:59
本文介绍了Python-测试属性引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出:

def test_to_check_exception_is_thrown(self):
    # Arrange
    c = Class()
    # Act and Assert
    self.assertRaises(NameError, c.do_something)

如果do_something引发异常,则测试通过.

If do_something throws an exception the test passes.

但是我有一个属性,当我用c.name = "Name"替换c.do_something时,我收到一条错误消息,提示我的测试模块未导入,并且Eclipse突出显示了等号.

But I have a property, and when I replace c.do_something with c.name = "Name" I get an error about my Test Module not being imported and Eclipse highlights the equals symbol.

如何测试属性会引发异常?

How do I test a property throws an exception?

setattrgetattr对我来说是新手.在这种情况下,他们当然有所帮助,谢谢.

setattr and getattr are new to me. They've certainly helped in this case, thanks.

推荐答案

assertRaises需要可调用的对象.您可以创建一个函数并将其传递:

assertRaises expects a callable object. You can create a function and pass it:

obj = Class()
def setNameTest():
    obj.name = "Name"        
self.assertRaises(NameError, setNameTest)

另一种可能性是使用setattr:

self.assertRaises(NameError, setattr, obj, "name", "Name")

您的原始代码引发语法错误,因为赋值是一条语句,不能放在表达式中.

Your original code raises a syntax error because assignment is a statement and cannot be placed inside an expression.

这篇关于Python-测试属性引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆