nose是第三方测试工具。比unittest进行测试更加简单。nose可以搜索测试用例并执行,可以发现用unittest编写的测试用例并执行。
可同时使用nose和unittest。
1、安装nose
$pip install nose
注: nose具测试发现功能, nose执行时,可从指定目录或者当前目录中找到测试用例
测试用例命令: test_* 或者 *_test
2、编写待测程序
例如:operation.py
class Operation(object):
def __init__(self):
self._result = 0
def add(self, x, y):
self._result = x + y
def sub(self, x, y):
self._result = x - y
3、编写测试类
继承unittest.TestCase, 编写测试用例
例如:test_operation.py
import unittest
class OperationTests(unittest.TestCase):
def _getTarget(self):
from operation import Operation
return Operation
def _makeOne(self, *args, **kwargs): #辅助方法,初始化被测对象
return self._getTarget()(*args, **kwargs)
def test_add(self):
target = self._makeOne()
target.add(1, 2)
self.assertEqual(target._result, 3)
def test_sub(self):
target = self._makeOne()
target.sub(5, 4)
self.assertEqual(target._result, 1)
4、执行测试
$ nosetests
转载于:https://blog.51cto.com/pythonfan/1607631