【发布时间】:2020-05-06 11:48:05
【问题描述】:
我正在使用 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 方法(在this_line 中),它将简单地打印一些东西并继续执行方法f。意思是,它将执行打印语句(在this_print)
实际程序中不应该是这种情况,当捕获到异常时,它将执行 sys.exit(1) 并停止程序。
当捕获到异常时,如何使用 unittest 和 mock 实现相同的效果我想停止执行此测试用例并继续执行下一个测试用例。
如何做到这一点?请帮忙
【问题讨论】:
-
您想在 catch 块内从 f 返回,但仅在测试期间?
-
如果是这样,将 try/catch 移到它自己的函数中
-
@geckos 将 try/catch 移动到它自己的函数中?
标签: python python-unittest python-mock