python 单元测试

需要测试的类

# Student.py

class Student(object):
    # __slots关键字可以限制类里只能添加什么属性,出了这里定义的属性其他属性一律不能添加
    __slots__ = ('_name', '_score', '_age')

    def __init__(self, name, score, age):
        self._name = name
        self._score = score
        self._age = age

    def print_score(self):
        print('%s %s' % (self._name, self._score))

    def say_hello(self):
        print('hello %s' % self._name)

    @property
    def name(self):
        return self._name

    @property
    def score(self):
        return self._score

    @property
    def age(self):
        return self._age

    @age.setter
    def age(self, value):
        if not isinstance(value, int):
            raise ValueError('age must be an integer')
        if value < 0 or value > 100:
            raise ValueError('age must between 0 ~ 100')
        self._age = value

    def __str__(self):
        return 'Student object (name:%s)' % self.__name

    __repr__ = __str__

测试用例文件

# TestStudent.py

import unittest

from Student import Student


class TestStudent(unittest.TestCase):

    def test_score(self):
        student = Student('java', 10, 20)
        self.assertGreaterEqual(student.score, 0, 'score must be larger than zero')

    def test_name(self):
        student = Student('java', 10, 20)
        self.assertEqual(student.name, 'java', 'name is not java')

    def test_age(self):
        student = Student('java', 10, 20)
        self.assertGreaterEqual(student.age, 0, 'age must be larger than zero')

那么如何运行单元测试呢,有两种方法,如下

  1. 第一种是直接运行python文件,但要在单元测试文件末尾加上如下代码
if __name__ == '__main__':
    unittest.main()

加上这行代码就可以使用命令行运行了如下

python3 TestStudent.py

  1. 第二种方式是不需要添加第一种提到的那两行代码就可以直接运行,只不过命令不一样,如下

python3 -m unittest TestStudent

很简单吧,最后这个参数TestStudent就是我们刚才写的那个测试用例文件名称

0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x