addCleanup vs tearDown

折月煮酒 提交于 2019-12-20 11:03:46

问题


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

If you are using unittest to write your tests, definitely use addCleanup, it's much better than 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.

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


It was also recently discussed in the Python unittest with Robert Collins podcast.


回答1:


Per the addCleanup doc string:

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

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.




回答2:


addCleanup() methods will run even if one of them fails, and will run even if setUp() fails. You should also consider using pytest.




回答3:


Another good thing about addCleanup is that it just works as you'd expect.

For example, if you call it in a setUp function, then all test methods will call the cleanup function in the end.

If you call it in a test method, only this method calls the cleanup function.



来源:https://stackoverflow.com/questions/37534021/addcleanup-vs-teardown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!