可以在 unittest tearDown 方法中断言吗? [英] Is it OK to assert in unittest tearDown method?

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

问题描述

我有一个带有多个测试的 TestCase,需要在每个测试结束时断言一些条件(每个测试都相同).将这些断言添加到 tearDown() 方法中是否可以,或者这是一个坏习惯,因为它们没有清理"任何东西?

I have a TestCase with multiple tests and need to assert a few conditions (the same for every test) at the end of each test. Is it OK to add these assertions to the tearDown() method, or is it a bad habit since they're not "cleaning" anything?

这样做的正确方法是什么?

What would be the right way of doing this?

推荐答案

Asserting something in your tearDown 意味着你需要注意在实际断言之前完成所有清理工作,否则清理代码如果 assert 语句失败并引发,则可能不会被调用.

Asserting something in your tearDown means that you need to be careful that all the cleaning is done before the actual asserting otherwise the cleaning code may not be called if the assert statement fails and raises.

如果断言只是一行,那么在每个测试方法中都可以使用它,如果它不仅仅是具有特定方法的可能性 - 该方法不应该是它自己的测试,即不被识别作为测试框架的测试.也可以使用方法装饰器或类装饰器.

If the assert is just one line it may be OK to have it in every test methods, if it is more than that having a specific method would be a possibility- that method should not be a test of its own i.e. not recognized as a test by your test framework. Using a method decorator or class decorator may also be an alternative.

总的来说,tearDown 不应该做任何测试,而且显式优于隐式.

Overall the idea is that tearDown shouldn't do any testing and that explicit is better than implicit.

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

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