python testcase,实例的Python unittest.TestCase的带参数

I would like to iterate over a list of items, and run an assertion on each of them. One example might be checking whether each number in a list is odd.

TestCase:

class TestOdd(unittest.TestCase):

def runTest(self):

"""Assert that the item is odd"""

self.assertTrue( NUMBER %2==1, "Number should be odd")

Test suite:

if __name__ == '__main__':

suite = unittest.TestSuite()

suite.addTest(TestOdd())

# I would like to have:

# suite.addTest(TestOdd(1))

# suite.addTest(TestOdd(2))

# suite.addTest(TestOdd(3))

# ...

unittest.main()

How can I instantiate a TestOdd object with an argument - for example, the number to be tested?

Update: According to a blog post from 2011 (posted as answer), there is no built-in mechanism for parametrized tests. I will be happy to accept any cleaner solutions.

解决方案

Same can be achieved using class attributes.

class TestOdd1(unittest.TestCase):

NUMBER=1

def runTest(self):

"""Assert that the item is odd"""

self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")

class TestOdd2(TestOdd1):

NUMBER=2

if __name__ == '__main__':

unittest.main()

The unittesting will discover them automatically, so no need to create a suite.

If you want to avoid using a TestCase for base class, you can use multiple inheritance:

from unittest import TestCase, main

class TestOdd:

def runTest(self):

"""Assert that the item is odd"""

self.assertTrue( self.NUMBER % 2 == 1, "Number should be odd")

class TestOdd1(TestOdd, TestCase):

NUMBER=1

class TestOdd2(TestOdd, TestCase):

NUMBER=2

if __name__ == '__main__':

main()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值