Unittest Framework 简明教程

UnitTest Framework - Unittest2

unittest2 是一个附加功能的后移植,这些功能已加入到 Python 2.7 和更高版本的 Python 测试框架中。它经过测试,可以在 Python 2.6、2.7 和 3.* 上运行。可以从 https://pypi.python.org/pypi/unittest2 下载最新版本。

unittest2 is a backport of additional features added to the Python testing framework in Python 2.7 and onwards. It is tested to run on Python 2.6, 2.7, and 3.*. Latest version can be downloaded from https://pypi.python.org/pypi/unittest2

要使用 unittest2,而不是 unittest,请用 import unittest2 替换 import unittest。

To use unittest2 instead of unittest, simply replace import unittest with import unittest2.

unittest2 中的类派生自 unittest 中相应的类,因此可以直接使用 unittest2 测试运行基础设施,无需立即将所有测试切换为使用 unittest2。如果你打算实现新功能,请将你的测试用例从 unittest2.TestCase 子类化,而不是 unittest.TestCase

Classes in unittest2 derive from the appropriate classes in unittest, so it should be possible to use the unittest2 test running infrastructure without having to switch all your tests to using unittest2 immediately. In case you intend to implement new features, subclass your testcase from unittest2.TestCase instead of unittest.TestCase

以下是 unittest2 的新功能 −

The following are the new features of unittest2 −

  1. addCleanups for better resource management

  2. Contains many new assert methods

  3. assertRaises as context manager, with access to the exception afterwards

  4. Has module level fixtures such as setUpModule and tearDownModule

  5. Includes load_tests protocol for loading tests from modules or packages

  6. startTestRun and stopTestRun methods on TestResult

在 Python 2.7 中,你可以使用 python -m unittest <args> 调用 unittest 命令行功能(包括测试发现)。

In Python 2.7, you invoke the unittest command line features (including test discover) with python -m unittest <args>.

而 unittest2 附带了一个脚本 unit2。

Instead, unittest2 comes with a script unit2.

unit2 discover
unit2 -v test_module