Chinaunix首页 | 论坛 | 博客
  • 博客访问: 835518
  • 博文数量: 253
  • 博客积分: 6891
  • 博客等级: 准将
  • 技术积分: 2502
  • 用 户 组: 普通用户
  • 注册时间: 2010-11-03 11:01
文章分类

全部博文(253)

文章存档

2016年(4)

2013年(3)

2012年(32)

2011年(184)

2010年(30)

分类: Python/Ruby

2011-06-15 13:24:07

ksks
  1. #!/usr/bin/python
  2. import unittest

  3. class myunitest(unittest.TestCase):
  4.     def setUp(self):
  5.         self.high = 10
  6.     def tearDown(self):
  7.         self.high = 0
  8.     def testhigh(self):
  9.         self.assertEqual(self.high, 9)
  10.         print 'the high is: %d' %self.high

  11. def suite():
  12.     suite = unittest.TestSuite()
  13.     suite.addTest(myunitest('testhigh'))
  14.     return suite

  15. if __name__ == '__main__':
  16.   
        #unittest.main(defaultTest = 'suite')
        #unittest.main()

        runner = unittest.TextTestRunner(open('./test.txt', 'w'))
        runner.run(suite())
  17.    
Notes:
  • 用import语句引入unittest模块。
  • 让所有执行测试的类都继承于TestCase类,可以将TestCase看成是对特定类进行测试的方法的集合。
  • setUp() and tearDown() methods provide a way to do setup or housekeeping before and after the test case is run. tearDown() is only run if setUp() succeeds (doesn't raise an exception). The test program treats errors in these methods as regular errors.
  • 在testhigh()中调用assertEqual()方法,值和预期值进行比较,确保两者是相等的,assertEqual()也是TestCase类中定义的方法。
  • 提供名为suite()的全局方法,PyUnit在执行测试的过程调用suit()方法来确定有多少个测试用例需要被执行,可以将TestSuite看成是包含所有测试用例的一个容器.
  • 默认情况下,TextTestRunner将结果输出到sys.stderr上,但如果在创建TextTestRunner类实例时将一个文件对象 传递给了构造函数,则输出结果将被重定向到该文件中。在Python的交互环境中驱动单元测试时,使用TextTestRunner类是一个不错的选择。

    PyUnit模块中定义了一个名为main的全局方法,使用它可以很方便地将一个单元测试模块变成可以直接运行的测试脚 本,main()方法使用TestLoader类来搜索所有包含在该模块中的测试方法,并自动执行它们。如果Python程序员能够按照约定(以test 开头)来命名所有的测试方法,那就只需要在测试模块的最后加入如下几行代码即可:unittest.main()

  • Make a class to hold a group of individual test cases.
  • The class derives from unittest.TestCase.

  • Make a new function for each test. Each test case should only test one thing!
  • Each test function name should start with 'test'.
  • If you include a docstring for the function, the first line will be printed if when there is an error. It's a simple way to document your test code.
  • Include a way to run this test case from the command line.
  • unittest.TestCase provides its own ways to assert errors- use them! Don't raise assertions yourself.

  • unittest.main() looks at all the classes that inherit from TestCase or TestSuite, and runs those tests cases.

  • addTest() adds an object to the TestSuite. Pass in an object derived from TestCase or TestSuite.

  • addTests() adds a list of objects to the TestSuite. Pass in a list of objects derived from TestCase or TestSuite.


阅读(527) | 评论(0) | 转发(0) |
0

上一篇:python os.path

下一篇:pyunittest 2 regression

给主人留下些什么吧!~~