Search code examples
python-3.xunit-testingexceptiontypeerrorpython-unittest

How to test assertRaised with arguments correctly?


I am trying to test (using unittest.TestCase) that a ValueError exception is raised when an invalid value is passed to the deposit method but the test is failing when it being is raised. I've stepped through the test in the debugger and it does reach the raise ValueError line but the test still fails for some reason. I've even tried raising and asserting with other exceptions and the test still fails.

Here is a debug image

My method:

    def deposit(self, amount):
        if (not isinstance(amount, float)) and (not isinstance(amount, int)):
            raise ValueError

My test:

    def test_illegal_deposit_raises_exception(self):
        self.assertRaises(ValueError, self.account.deposit("Money"))

I then thought that perhaps it was failing becasue the exception had not yet been caught. So I added a method in my object's class to call the deposit method catch the ValueError Exception.

    def aMethod(self):
        try:
            self.deposit("Money")
        except ValueError:
            print("ValueError was caught")

However, now the test failed because I am getting a TypeError Exception instead. Here is an other debug image

TypeError: 'NoneType' object is not callable

Could someone explain why I am getting a TypeError Exception instead of the ValueError Exception which I've raised?


Solution

  • After looking at this answer by Daryl Spitzer I was able to get it working.

    Python docs for assertRaises() - Since assertRaises() calls the deposit() method provided, I needed to provide the call arguments in the assertRaises() arguments - instead of in the deposit() method call.

    The correct way to test the Exception is raised:

    self.assertRaises(ValueError, self.account.deposit, "Money")
    

    The wrong way:

    self.assertRaises(ValueError, self.account.deposit("Money"))