Python - test a property throws exception
Since Python 2.7 and 3.1 assertRaises()
can be used as a context manager. See here for Python 2 and here for Python3.
So you can write your test with the with
instruction like this:
def test_to_check_exception_is_thrown(self):
c = Class()
with self.assertRaises(NameError):
c.name = "Name"
assertRaises
expects a callable object. You can create a function and pass it:
obj = Class()
def setNameTest():
obj.name = "Name"
self.assertRaises(NameError, setNameTest)
Another possibility is to use 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.