sic*_*ini 4 python unit-testing python-unittest
假设我有以下 Python UnitTest:
import unittest
def Test(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Get some resources
...
if error_occurred:
assert(False)
@classmethod
def tearDownClass(cls):
# release resources
...
Run Code Online (Sandbox Code Playgroud)
如果 setUpClass 调用失败,则不会调用 tearDownClass,因此永远不会释放资源。如果下一次测试需要资源,这在测试运行期间会出现问题。
当 setUpClass 调用失败时,有没有办法进行清理?
与保护其他地方的资源的方式相同。 try-except:
def setUpClass(cls):
# ... acquire resources
try:
# ... some call that may fail
except SomeError, e:
# cleanup here
Run Code Online (Sandbox Code Playgroud)
清理可能就像cls.tearDownClass()在您的except块中调用一样简单。 然后你可以调用assert(False)或任何你喜欢的方法提前退出测试。
您可以在 setUpClass 方法中放置一个 try catch 并直接调用 except 中的 tearDown。
def setUpClass(cls):
try:
# setUpClassInner()
except Exception, e:
cls.tearDownClass()
raise # to still mark the test as failed.
Run Code Online (Sandbox Code Playgroud)
需要外部资源来运行单元测试是不好的做法。如果这些资源不可用,并且您需要测试部分代码是否存在奇怪的错误,您将无法快速运行它。尝试将集成测试与单元测试区分开来。
与此同时,出于这个目的,addClassCleanup添加了类方法: https://docs.python.org/3/library/unittest.html#unittest.TestCase.addClassCleanupunittest.TestCase
| 归档时间: |
|
| 查看次数: |
8398 次 |
| 最近记录: |