Pyunit源码笔记之十 pyunit运行方式之一:直接调用

通过上面的分析,文章二,三,四,即创建testcase,testsuit,开始运行run,这几个步骤,我们可以自己来指定,很简单。

简单的创建 一个test case,

根据测试用例文件写的类如下:
class MyTest(unittest.TestCase):
    def setUp(self):
        print("Set up...")
        self.myclassa = MyClassA.MyClassA()
    
    def testsum(self, a = 4, b = 5): 
        self.assertEqual(self.myclassa.addMy(a, b), a * b)
    
    def testmul(self, a = 4, b = 5): 
        self.assertEqual(self.myclassa.mulMy(a, b), a * b)
        
    def tearDown(self):
        print("Tear down...")
        pass  

直接实例化测试用例类,和实例化被测类
mytestcase = MyTest()
mytestcase.myclassa = MyClassA.MyClassA()

然后调用其中的测试方法:

mytestcase.testsum(5,6)
mytestcase.testmul(5,6)

当然这种直接调用,没办法享受到setup和teardown.
这是最原始的方法,当然也可以用。

下面根据框架的testcase类,创建testcase实例,先看testcasse类的初始化:
    def __init__(self, methodName='runTest'):
        """Create an instance of the class that will use the named test
           method when executed. Raises a ValueError if the instance does
           not have a method with the specified name.
        """
        self._testMethodName = methodName
        self._outcome = None
        self._testMethodDoc = 'No test'
        try:
            testMethod = getattr(self, methodName)
        except AttributeError:
            if methodName != 'runTest':
                # we allow instantiation with no explicit method name
                # but not an *incorrect* or missing method name
                raise ValueError("no such test method in %s: %s" %
                      (self.__class__, methodName))
        else:
            self._testMethodDoc = testMethod.__doc__
        self._cleanups = []
        self._subtest = None

就一个参数,测试方法methodName='runTest',默认的是runTest,这里我们初始化如下:

testcase1 = MyTest("testsum")
testcase2 = MyTest("testmul")

运行的话,直接调用其run方法:

runner = unittest.TextTestRunner()
runner.run(testcase1)
runner.run(testcase2)
这种方式会调用setup和teardown方法。

你可能感兴趣的:(python,unittest源码分析,pyunit)