添加清理 vs 拆除

2024-05-13 22:14:44 发布

您现在位置:Python中文网/ 问答频道 /正文

最近,Ned Batchelder在his talk at PyCon 2016期间指出:

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

到目前为止,我从未使用过addCleanup(),并且习惯了setUp()/tearDown()对测试“设置”和“拆卸”阶段的方法。在

为什么要切换到addCleanup()而不是tearDown()?在


最近在Python unittest with Robert Collins播客中也讨论过这个问题。在


Tags: toyouifunittestareatwritetalk
3条回答

关于addCleanup的另一个好处是它可以像您预期的那样工作。在

例如,如果在setUp函数中调用它,那么所有测试方法最后都将调用cleanup函数。在

如果在测试方法中调用它,则只有此方法调用cleanup函数。在

addCleanup()方法即使其中一个失败也将运行,即使setUp()失败也将运行。您还应该考虑使用pytest。在

根据^{} doc string

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

addCleanup可用于注册多个函数,因此可以使用 为要清理的每个资源分别设置函数。这会让你 代码更加可重用/模块化。在

相关问题 更多 >