NBajanca
NBajanca

Reputation: 3730

assertRaises for method with optional parameters

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

Answers (2)

Shamsiddin Parpiev
Shamsiddin Parpiev

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

NBajanca
NBajanca

Reputation: 3730

Two ways to do it:

  1. Just like in the question but putting the args:

    def test_method(self):        
        self.assertRaises(ExampleException, example_method, "some_var", 
                          optional_var="not_none")
    
  2. With with:

    Like explained in Python Docs:

    def test_method(self):
        with self.assertRaises(ExampleException):
            example_method("some_var", "not_none")
    

Upvotes: 15

Related Questions