4. Test code组织结构
4.1 在unittest中,test case都是测试类的实力,所以编写testcase时,必须预先定义测试子类。继承自Testcase或者FunctionTestcase。
Testcase提供的
assert*()方法是用于检测测试结果,
官方说明:
Note that in order to test something, we use one of the
assert*()
methods provided by the
TestCase
base class. If the test fails, an exception will be raised, and
unittest
will identify the test case as a
failure. Any other exceptions will be treated as
errors. This helps you identify where the problem is:
failures are caused by incorrect results - a 5 where you expected a 6.
Errors are caused by incorrect code - e.g., a
TypeError
caused by an incorrect function call.
例子:
import unittest
class WidgetTestCase(unittest.TestCase): def setUp(self): self.widget = Widget('The widget') def tearDown(self): self.widget.dispose() self.widget = None def test_default_size(self): self.assertEqual(self.widget.size(), (50,50), 'incorrect default size') def test_resize(self): self.widget.resize(100,150) self.assertEqual(self.widget.size(), (100,150), 'wrong size after resize')
(1)如果setUp()succeed, tearDown()不管testcase是否成功都会执行。
如果setUp() failed, testcase不执行
(2)我们可以指定执行某一个testcase