views:

101

answers:

3

Given:

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

If do_something throws an exception the test passes.

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?

Edit:

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

A: 

You're getting an error because it's a syntax error in Python to have an assignment inside another expression. For example:

>>> print(foo = 'bar')
------------------------------------------------------------
   File "<ipython console>", line 1
     print(foo = 'bar')
               ^
SyntaxError: invalid syntax

But doing it in two steps works fine:

>>> foo = 'bar'
>>> print(foo)
bar

To test that a property throws an exception, use a try block:

try:
   object.property = 'error'
except ExpectedError:
   test_passes()
else:
   test_fails()
samtregar
This is overkill and doesn't really fit into using unittest.
Noufal Ibrahim
+2  A: 

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

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

Another possibility is to use setattr:

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

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

interjay
+2  A: 

The second argument to failUnlessRaises should be a callable.

An assignment statement (ie. class.name = "Name") is not a callable so it will not work. Use setattr to perform the assignment like so

self.failUnlessRaises(NameError, setattr, myclass, "name", "Name")

Also, you can't assign to class since it's a keyword.

Noufal Ibrahim
It was pseudo code, to mirror my code. But I know ;)
Finglas