我什么时候应该使用 setUpClass 以及 __init__ 什么时候? [英] When should I use setUpClass and when __init__?

查看:83
本文介绍了我什么时候应该使用 setUpClass 以及 __init__ 什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两种方法在运行时逻辑上有什么区别吗?或者任何行为差异?
如果没有,那么我是否应该忘记 __init__ 并只使用 setUpClass 在这里考虑单元测试类,例如命名空间而不是语言 OOP 范式?

Is there any runtime-logic difference between these two methods? Or any behviour differences?
If not, then should I forget about __init__ and use only setUpClass thinking here about unittests classes like about namespaces instead of language OOP paradigm?

推荐答案

两者完全不同.

setUpClass 是一个类方法,例如,它只会让你设置 class 属性.

setUpClass is a class method, for one, so it'll only let you set class attributes.

它们也在不同的时间被调用.测试运行器为每个测试创建一个新实例.如果您的测试类包含 5 个测试方法,则会创建 5 个实例并且 __init__ 被调用 5 次.

They are also called at different times. The test runner creates a new instance for every test. If your test class contains 5 test methods, 5 instances are created and __init__ is called 5 times.

setUpClass 通常只调用一次.(如果你打乱了测试顺序和来自不同类的测试方法混合在一起,setUpClass 可以被多次调用,使用 tearDownClass 正确清理,这不会是一个问题).

setUpClass is normally called only once. (If you shuffle up test ordering and test methods from different classes are intermingled, setUpClass can be called multiple times, use tearDownClass to clean up properly and that won't be a problem).

此外,测试运行器通常会在测试运行开始时创建所有测试实例;这通常很便宜,因为测试实例不会保存(很多)状态,因此不会占用太多内存.

Also, a test runner usually creates all test instances at the start of the test run; this is normally cheap, as test instances don't hold (much) state so won't take up much memory.

根据经验,您根本不应该使用__init__.使用 setUpClass 创建所有测试之间共享的状态,并使用 setUp 创建每个测试的状态.setUp 在测试运行之前调用,因此您可以避免在测试需要之前而不是之前建立大量内存密集型状态.

As a rule of thumb, you should not use __init__ at all. Use setUpClass to create state shared between all the tests, and use setUp to create per-test state. setUp is called just before a test is run, so you can avoid building up a lot of memory-intensive state until it is needed for a test, and not before.

这篇关于我什么时候应该使用 setUpClass 以及 __init__ 什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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