Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 371
NBajanca Avatar asked Aug 09 '16 16:08

NBajanca


People also ask

What happens if we do not pass any parameter to optional arguments?

If we do not pass any parameter to the optional arguments, then it takes its default value. The default value of an optional parameter is a constant expression. The optional parameters are always defined at the end of the parameter list. Or in other words, the last parameter of the method, constructor, etc. is the optional parameter.

How to deal with optional parameters in Java?

Introduction to optional parameters in Java. Unlike some languages such as Kotlin and Python, Java doesn’t provide built-in support for optional parameter values. Callers of a method must supply all of the variables defined in the method declaration. In this article, we’ll explore some strategies for dealing with optional parameters in Java.

Can the default value of an optional parameter be overridden?

When calling a method, the caller cannot override the default value of the final optional parameter unless the caller also overrides the default values of every other optional parameter. In the following example, the first method has two optional parameters.

How to make a variable optional in a method?

varargs could do that (in a way). Other than that, all variables in the declaration of the method must be supplied. If you want a variable to be optional, you can overload the method using a signature which doesn't require the parameter.


1 Answers

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")
    
like image 60
NBajanca Avatar answered Nov 05 '22 16:11

NBajanca