添加清理与拆卸 [英] addCleanup vs tearDown

查看:35
本文介绍了添加清理与拆卸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,Ned Batchelder 在 他在 PyCon 2016 上的演讲 指出:

Recently, Ned Batchelder during his talk at PyCon 2016 noted:

如果您使用 unittest 编写测试,请务必使用addCleanup,比tearDown好多了.

If you are using unittest to write your tests, definitely use addCleanup, it's much better than tearDown.

到目前为止,我从未使用过 addCleanup() 并习惯了 setUp()/tearDown() 对方法用于测试设置"和拆除"阶段.

Up until now, I've never used addCleanup() and got used to setUp()/tearDown() pair of methods for test "set up" and "tear down" phases.

为什么我应该切换到 addCleanup() 而不是 tearDown()?

Why should I switch to addCleanup() instead of tearDown()?

最近在 与 Robert Collins 的 Python 单元测试中也讨论了这个问题 播客.

推荐答案

根据 <代码>addCleanup 文档字符串:

Per the addCleanup doc string:

即使 setUp 失败也会调用清理项(与 tearDown 不同)

Cleanup items are called even if setUp fails (unlike tearDown)

addCleanup 可以用来注册多个函数,所以你可以使用您希望清理的每个资源的单独功能.那会让你的代码更可重用/模块化.

addCleanup can be used to register multiple functions, so you could use separate functions for each resource you wish to clean up. That would allow your code to be a bit more reusable/modular.

这篇关于添加清理与拆卸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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