我正在使用 unittest 和 mock 来测试一个看起来像这样的脚本
class Hi:
def call_other(self):
perform some operation
sys.exit(1)
def f(self):
try:
res = self.do_something()
a = self.something_else(res)
except Exception as e:
print(e)
call_other()
print("hi after doing something") -----> (this_print)
def process(self)
self.f()
我的测试脚本看起来像这样
class Test_hi(unittest.TestCase)
def mock_call_other(self):
print("called during error")
def test_fail_scenario():
import Hi class here
h = Hi()
h.process()
h.do_something = mock.Mock(retrun_value="resource")
h.something_else = mock.Mock(side_effect=Exception('failing on purpose for testing'))
h.call_other(side_effect=self.mock_call_other) -----> (this_line)
如果我不模拟call_other方法,它将调用 sys.exit(1) 并且会在 unittest 运行中导致一些问题,所以,我不想call_other在测试期间调用 sys.exit(1) 。但是,如果我像上面那样模拟call_other方法(in this_line),它将简单地打印一些东西并继续执行 method f。意思是,它将执行 print 语句(in this_print)这在实际程序中不应该是这种情况,当捕获到异常时,它将执行 sys.exit(1) 并停止程序。当捕获到异常时,如何使用 unittest 和 mock 实现相同的目标我想停止执行此测试用例并继续执行下一个测试用例。
如何做到这一点?请帮忙
达令说
相关分类