[英]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
?如何在
unittest
或mock
引发ZeroDivisionError
、 AttributeError
等?
If object
is an instance of your class such that object.b = 0 then you can do this如果
object
是你的类的一个实例,这样 object.b = 0 那么你可以这样做
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同样,您可以创建生成其他两个错误的类的实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.