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方法。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值