注册方法在python unittest中的tearDown运行? [英] Register method to run at tearDown in python unittest?

查看:43
本文介绍了注册方法在python unittest中的tearDown运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个方案
00 模拟一些方法并立即注册取消模拟的方法调用
01 插入一些fixture行来测试数据库并注册方法调用以立即清理它们

I have two scenario for this
00 mock some method and register the method call for unmock right away
01 insert some fixture rows to test database and register the method call to clean them up right away

我可以在 tearDown() 中调用这些 cleanup 方法,但这会出现在我的数百个测试类中.

I can call these clean up method at tearDown() but that will appear in hundreds of my test classes.

有没有办法注册tearDown()调用时会执行的方法?

Is there any way to register method that will be executed when tearDown() called?

附言

我的搜索对谷歌没有帮助 这里,以及我们的stackoverflow 这里

My search not helpful with google here, and on our stackoverflow here

推荐答案

使用 addCleanup() 试试

import unittest


def my_code(my_var):
  print(f'in my_code with my_var={my_var}')


class Test(unittest.TestCase):

  def test(self):
      # your test goes here
      self.addCleanup(my_code, my_var='some value')  # register this clean up when test ended

这篇关于注册方法在python unittest中的tearDown运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆