首页 > 解决方案 > 如何为班级编写单元测试?

问题描述

class Hand:

def __init__(self,cards, total, soft_ace_count):
    self.cards = cards
    self.total = total
    self.soft_ace_count = soft_ace_count


def __str__(self):
    return(str(self.cards)+','+str(self.total)+','+str(self.soft_ace_count))


def add_card(self):
    self.cards.append(get_card())
    self.score()


def is_blackjack(self):
    return len(self.cards)==2 and self.total==21


def is_bust(self):
    return self.total > 21

def score(self):
    self.total=0
    self.soft_ace_count=0

    for x in self.cards:
        if x > 10:
            x=10
        self.total+=x

    #the following code will decide 1 =11 or 1 = 1
    if self.total <= 11 and 1 in self.cards:
        self.total+=10
        self.soft_ace_count+=1

我正在尝试为这个“手”类编写单元测试。我需要为这个特定的单元测试进行初始化设置吗?这是我的单元测试代码的一部分。如果有人能帮我解决这个问题,非常感谢。我刚开始使用python。任何建议都会有所帮助。谢谢你。忽略缩进

class hand(unittest.TestCase):

def __init__(self):
    self.cards=cards
    self.total = total
    self.soft_ace_count = soft_ace_count

标签: python-3.xpython-unittest

解决方案


假设您的类在名为 hand.py 的模块中,您可以将 unittest 脚本放在同一目录中。它可能看起来像这样:

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()

如果你将你的 unittestscript 命名为 unittesthand.py,你可以通过“python unittestscript.py”运行它。您将得到以下结果:

> .
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

unittest 组件已执行所有以“test”开头的方法并执行。在示例中,“test_init”方法。这不是测试的初始化,而是 Hand 类初始化的单元测试。

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

现在您可以为其他方法创建额外的案例。您还可以使用始终在单元测试之前和之后执行的代码创建一个基本测试案例等等......


推荐阅读