Home > OS >  How to use assertEqual with two inputs of a function?
How to use assertEqual with two inputs of a function?

Time:11-15

Newbie here, sorry in advance! I tried looking for answers in other Stack posts on unit testing/ the assertEqual function but didn't find an answer to what I was looking for.

In a case when there is one input in a function, you could set up a unit-test as follows:

def test_some_function(self):
        inputted = 2
        some_function(inputted)
        output_expected = 3 #made up an expected output
        self.assertEqual(output_expected, inputted)

But how would you use self.assertEqual when your function takes two inputs?

I tried the below, but this runs into positional issues with self:

def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        some_function(inputted_one, inputted_two)
        output_expected = 3 
        self.assertEqual(output_expected, inputted_one, inputted_two) 

And I want to avoid setting a value to the function output, likeso:

def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        set_value = some_function(inputted_one, inputted_two)
        output_expected = 3
        self.assertEqual(output_expected, set_value) 

EDIT I also want to avoid something like

self.assertEqual(output_expected, some_function(inputted_one, inputted_two)) because self.assertEqual should already be applying the function to the inputs.

ie, with one input it was not necessary to do self.assertEqual(output_expected, some_function(inputted_one)

CodePudding user response:

You can put the function output in the assert like this:

def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        output_expected = 3 
        self.assertEqual(output_expected,some_function(inputted_one, inputted_two))

CodePudding user response:

here:

def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        some_function(inputted_one, inputted_two)
        output_expected = 3 
        self.assertEqual(output_expected, inputted_one, inputted_two) 

you are comparing and output with 2 inputs (inputted_one, inputted_two), which is kind of weird.

If you would like to compare a function output with an expected output, you can write:

def test_some_function(self):
        inputted_one = 1
        inputted_two = 2
        function_output = some_function(inputted_one, inputted_two)
        output_expected = 3 
        self.assertEqual(output_expected, function_output)

or a shorter version

def test_some_function(self):
        self.assertEqual(3, some_function(1, 2))
  • Related