Home > Backend Development > Python Tutorial > Python单元测试框架unittest简明使用实例

Python单元测试框架unittest简明使用实例

WBOY
Release: 2016-06-10 15:15:27
Original
1473 people have browsed it

测试步骤
1. 导入unittest模块
import unittest

2. 编写测试的类继承unittest.TestCase
class Tester(unittest.TestCase)

3. 编写测试的方法必须以test开头
def test_add(self)
def test_sub(self)

4.使用TestCase class提供的方法测试功能点

5.调用unittest.main()方法运行所有以test开头的方法

复制代码 代码如下:

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

实例如下
被测试类

复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8

class Computer(object):
 @staticmethod
 def add(a, b):
  return a + b;
 
 @staticmethod
 def sub(a, b):
  return a - b; 

测试类

复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8
import unittest
from Testee import Computer

class Tester(unittest.TestCase): 
 def test_add(self):
  self.assertEqual(Computer.add(2, 3), 5, "test add function")
  
 def test_sub(self):
  self.assertEqual(Computer.sub(5, 1), 4, "test sub function") 

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

​运行结果:

复制代码 代码如下:

----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template