Python 3.x 如何为类编写单元测试?

Python 3.x 如何为类编写单元测试?,python-3.x,python-unittest,Python 3.x,Python Unittest,假设类位于名为hand.py的模块中,则可以将unittest脚本放在同一目录中。它可能是这样的: class hand(unittest.TestCase): def __init__(self): self.cards=cards self.total = total self.soft_ace_count = soft_ace_count 如果将unittestscript命名为unittesthand.py,则可以通过“PythonUnitTestScript

假设类位于名为hand.py的模块中,则可以将unittest脚本放在同一目录中。它可能是这样的:

class hand(unittest.TestCase):

def __init__(self):
    self.cards=cards
    self.total = total
    self.soft_ace_count = soft_ace_count
如果将unittestscript命名为unittesthand.py,则可以通过“PythonUnitTestScript.py”运行它。您将得到以下结果:

import unittest
from hand import Hand

class hand(unittest.TestCase):

    def test_init(self):
        cards = []
        h = Hand(cards, 0, 0)
        self.assertEqual(h.total, 0)
        self.assertEqual(h.soft_ace_count, 0)
        self.assertEqual(len(h.cards), 0)

    # def test_blackjack(self):
        #....


    # def test_score(self):
        #.... 


    # def test_OTHERTHINGS(self):
        #.....

if __name__ == '__main__':
    unittest.main()
unittest组件已经执行了所有以“test”开头并已执行的方法。在本例中,使用“test_init”方法。这不是测试的初始化,而是类Hand初始化的unittest

例如,现在将代码更改为“self.assertEqual(h.total,1)”,您将看到unittest组件报告错误

现在,您可以为其他方法创建其他案例。您还可以创建一个基本测试案例,其中的代码始终在unittests之前和之后执行,等等

import unittest
from hand import Hand

class hand(unittest.TestCase):

    def test_init(self):
        cards = []
        h = Hand(cards, 0, 0)
        self.assertEqual(h.total, 0)
        self.assertEqual(h.soft_ace_count, 0)
        self.assertEqual(len(h.cards), 0)

    # def test_blackjack(self):
        #....


    # def test_score(self):
        #.... 


    # def test_OTHERTHINGS(self):
        #.....

if __name__ == '__main__':
    unittest.main()
> .
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK