unittest learning

Basic example

 

 1 import unittest
 2 
 3 class TestStringMethods(unittest.TestCase):
 4 
 5     def test_upper(self):
 6         self.assertEqual('foo'.upper(), 'FOO')
 7 
 8     def test_isupper(self):
 9         self.assertTrue('FOO'.isupper())
10         self.assertFalse('Foo'.isupper())
11 
12     def test_split(self):
13         s = 'hello world'
14         self.assertEqual(s.split(), ['hello', 'world'])
15         # check that s.split fails when the separator is not a string
16         with self.assertRaises(TypeError):
17             s.split(2)
18 
19 if __name__ == '__main__':
20     unittest.main()

 

The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. 

unittest.main() provides a command-line interface to the test script

 

 Command-Line Interface

1 python -m unittest test_module1 test_module2 

2 python -m unittest test_module.TestClass

3 python -m unittest test_module.TestClass.test_method
 

You can pass in a list with any combination of module names, and fully qualified class or method names.

Organizing test code

Tests can be numerous, and their set-up can be repetitive. Luckily, we can factor out set-up code by implementing a method called setUp(), which the testing framework will automatically call for every single test we run:

 1 import unittest
 2 
 3 class WidgetTestCase(unittest.TestCase):
 4     def setUp(self):
 5         self.widget = Widget('The widget')
 6 
 7     def test_default_widget_size(self):
 8         self.assertEqual(self.widget.size(), (50,50),
 9                          'incorrect default size')
10 
11     def test_widget_resize(self):
12         self.widget.resize(100,150)
13         self.assertEqual(self.widget.size(), (100,150),
14                          'wrong size after resize')

tearDown() method that tidies up after the test method has been run

If setUp() succeeded, tearDown() will be run whether the test method succeeded or not

 

 

 

转载于:https://www.cnblogs.com/cppb/p/6220249.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值