一直以为 TestCase 中的 setUp( ) 与 tearDown( ) 是针对 整个TestCase 的
昨天 偶然发现 原来不是这个样子.这两个方法都是在每个测试方法先后调用,帮助上是这么写的
setUp( )
Method called to prepare the test fixture. This is called immediately before calling the test method; any exception raised by this method will be considered an error rather than a test failure. The default implementation does nothing.
tearDown( )
Method called immediately after the test method has been called and the result recorded. This is called even if the test method raised an exception, so the implementation in subclasses may need to be particularly careful about checking internal state. Any exception raised by this method will be considered an error rather than a test failure. This method will only be called if the setUp() succeeds, regardless of the outcome of the test method. The default implementation does nothing.
相关代码如下,TestCase 中的__Call__
def __call__(self, result=None):
if result is None: result = self.defaultTestResult()
result.startTest(self)
testMethod = getattr(self, self.__testMethodName)
try:
try:
self.setUp()
except KeyboardInterrupt:
raise
except:
result.addError(self, self.__exc_info())
return
ok = 0
try:
testMethod()
ok = 1
except self.failureException:
result.addFailure(self, self.__exc_info())
except KeyboardInterrupt:
raise
except:
result.addError(self, self.__exc_info())
try:
self.tearDown()
except KeyboardInterrupt:
raise
except:
result.addError(self, self.__exc_info())
ok = 0
if ok: result.addSuccess(self)
finally:
result.stopTest(self)
本文解析了unittest框架中setUp与tearDown方法的作用及调用时机。它们并非针对整个测试类,而是在每个测试方法前后分别调用,用于准备和清理测试环境。
3724

被折叠的 条评论
为什么被折叠?



