简体   繁体   English

如何在单元测试中为测试异常生成错误?

[英]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 ?如何在unittestmock引发ZeroDivisionErrorAttributeError等?

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.

相关问题 pytest或python中的任何测试工具能否自动生成单元测试? - Can pytest or any testing tool in python generate the unit test automatically? 如何测试是否使用单元测试引发和捕获了正确的异常? - How to test if the right exception is raised and caught using unit testing? 单元测试:如何动态导入测试类并运行? - Unit testing: How can i import test classes dynamically and run? 在单元测试中,如何确定传递给自定义异常的参数? - In a unit test, how can the parameter passed to a custom exception be determined? 查找密钥 [user] 失败<User: test>单元测试时的异常 - Failed lookup for key [user] in <User: test> exception when unit testing 如何为方法生成单元测试代码 - how to generate unit test code for methods 我的单元测试中可以包含哪些其他测试用例? - What additional test cases can be included in my Unit Testing? 如何在我的单元测试中模拟 ParameterNotFound boto3 异常? - How can I simulate a ParameterNotFound boto3 exception in my unit test? (如何像计算机科学家一样思考-6.3单元测试)使用测试还是单元测试进行单元测试 - (How to Think like a Computer Scientist - 6.3 Unit Testing) Unit Testing using test vs unittest 引发异常的单元测试方法 - Unit testing method that raises and exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM