Reputation: 3730
I'm using assertRaises
for unit test in Django.
Example method I want to test:
def example_method(var, optional_var=None):
if optional_var is not None:
raise ExampleException()
My test method:
def test_method(self):
self.assertRaises(ExampleException, example_method, ???)
How should I pass the arguments to raise the exception?
Upvotes: 8
Views: 4875
Reputation: 99
Also there is more neater and cleaner way with using lambda:
def foo(name):
if name == 'shams':
raise ValueError
# then in your test case
self.assertRaises(ValueError, lambda: foo('shams'))
Upvotes: 1
Reputation: 3730
Two ways to do it:
Just like in the question but putting the args:
def test_method(self):
self.assertRaises(ExampleException, example_method, "some_var",
optional_var="not_none")
With with
:
Like explained in Python Docs:
def test_method(self):
with self.assertRaises(ExampleException):
example_method("some_var", "not_none")
Upvotes: 15