python - 使用单元测试 unittest, from X import *, String interpolation, self, class method, instance method, static method

访问量: 127

单元测试的最简单例子

例子如下:

import unittest

class MyClass(unittest.TestCase):
    def test_hi(self):
        self.assertEqual(1+1, 2)

if __name__ == '__main__':
    unittest.main()
          

定义一个class, 包含 instance, class , static method

class Hi():
    def instance_say_hi(self):
        print(f'-- self: {self}')  # 注意: 这里的 f'{self}'  就是string interpolation , >= python3.6 有效
        return "hi"
    
    @classmethod
    def class_method_say_hi(this_class):
        print(f'-- this_class: {this_class}')
        return "hi from class_method_say_hi"
    
    @staticmethod
    def static_method_say_hi():
        return "hi from static_method_say_hi"

定义对应的单元测试文件

import unittest
from Hi import *   # 注意,这里不能简单的使用  import Hi , 会报错  

hi = Hi()

class MyClass(unittest.TestCase):
    def test_sum(self):
        self.assertEqual(1+1, 2)

    def test_hi(self):
        hi = Hi()
        self.assertEqual(hi.instance_say_hi(), 'hi')
        self.assertEqual(hi.class_method_say_hi(), 'hi from class_method_say_hi')
        self.assertEqual(Hi.class_method_say_hi(), 'hi from class_method_say_hi')
        self.assertEqual(Hi.static_method_say_hi(), 'hi from static_method_say_hi')

if __name__ == '__main__':
    unittest.main()

运行即可:  $ python3 test_hi.py

订阅/RSS Feed

Subscribe

分类/category