Search code examples
pythondjangounit-testingmockingpython-unittest

How can to generate error for testing exception in unit test?


I have same code:

def foo(self):
  x = self.a + self.b
  try:
    res = self.a / self.b
  except ZeroDivisionError:
    res = foo_2()
  except AttributeError:
    res = foo_3()
  except CustomError:
    res = foo_4()
  except RemoteAPIError:
    res = foo_5()
  return res

def foo_2():
  ...

def foo_3():
  ...

def foo_4():
  ...

def foo_5():
  ...

How can to raise ZeroDivisionError, AttributeError etc in unittest or mock?


Solution

  • If object is an instance of your class such that object.b = 0 then you can do this

       import pytest
       from unittest.mock import MagicMock
    
       object.foo_2 = MagicMock() 
       with pytest.raises(ZeroDivisionError):
           object.foo()
       object.foo_2.assert_called_once()
    

    Similarly, you can create instances of your class that generate the other two errors