写好unit test的建议和例子
最近翻了下写unit test 的文章,总结如下
What’s unit test?
“Unit testing is a software testing method by which individual units of source code.” – –Wikipedia
What’s integration test?
“Integration testing is the phase in software testing in which individual software modules are combined and tested as a group” – Wikipedia
Goal for unit test
- Defects obvious bugs
- Provide an example about how to call it
- Refactor
Effective way to find bugs
- Integration test
- Manual test
How to write good unit test?
Arrange -> Act -> Assert
# zoo.py
class Zoo: def __init__(self, animals):
self.animals = animals def sort_by_name(self):
self.animals = sorted(self.animals) def get_animals(self):
return self.animals # test_zoo.py
import unittest class Zoo: def __init__(self, animals):
self.animals = animals def sort_by_name(self):
self.animals = sorted(self.animals) def get_animals(self):
return self.animals class TestZoo(unittest.TestCase): def test_sort_by_name(self):
# Arrange: Set up test data
bj_zoo = Zoo(['panda', 'elephant', 'tiger']) # Act: Execute the unit under test
bj_zoo.sort_by_name() # Assert: Verify and log the result
self.assertEqual(bj_zoo.animals[0], 'elephant')
Tests verify facts about the application, not exact results
Separate requirements into individual clauses
import cipher
import decrypt
import unittest def encrypt(str): # Encryption followed by decryption should return the original:
# the encrypted text is as long as the original:
# no character is encrypted to itself:
entrypted_str = cipher.encrypt(str) return entrypted_str class TestEncypt(unittest.TestCase): def test_encrypt_bad(self):
actual_encryption = encrypt('hello')
expected_encryuption = 'ASDFG'
self.assertEqual(actual_encryption, expected_encryuption) def test_encrypt_good(self): original_str = 'hello'
self.assertEqual(original_str, decrypt(encrypt(original_str))) self.assertEqual(len(original_str), len(encrypt(original_str))) for i in xrange(0, len(original_str)):
self.assertNotEqual(original_str[i], encrypt(original_str))
Test exception handling
import unittest
from exceptions import ValueError def raise_exception():
raise ValueError('error msg foo') class TestRaiseException(unittest.TestCase): def test_raise_exception(self):
self.assertRaises(ValueError, raise_exception)
Don’t only test one input value or state
import unittest
from ddt import ddt, data, unpack def larger_than_two(num):
if num > 2:
return True @ddt
class FooTestCase(unittest.TestCase): @data(3, 4, 12, 23)
def test_larger_than_two(self, value):
self.assertTrue(larger_than_two(value)) @data((3, 2), (4, 3), (5, 3))
@unpack
def test_tuples_extracted_into_arguments(self, first_value, second_value):
self.assertTrue(first_value > second_value)
Mock out all external services and state
# rm.py
import os def rm(filename):
os.remove(filename) # test_rm.py
from rm import rm
import mock
import unittest import os def rm(filename):
os.remove(filename) class RmTestCase(unittest.TestCase):
@mock.patch('foomodule.os')
def test_rm(self, mock_os):
rm("any path")
mock_os.remove.assert_called_with("any path")
Avoid unnecessary preconditions
Name clearly and consistently
Example
test_divide_zero_raise_exception
When and where to add unit test?
- When you need a block of comment
- Parts likely to fail
- Parts keep getting questions
Reference
https://developer.salesforce.com/page/How_to_Write_Good_Unit_Tests
http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/
http://www.ibm.com/developerworks/cn/linux/l-tdd/index.html
https://msdn.microsoft.com/en-us/library/jj159340.aspx
写好unit test的建议和例子的更多相关文章
- 写几个简单用artTemplate的例子
写几个简单的artTemplate的例子,很多框架都有自己的模板(template),没得时候,可以利用artTemplate.js完成 html文件是: <!DOCTYPE html> ...
- 微软手写识别模块sdk及delphi接口例子
http://download.csdn.net/download/coolstar1204/2008061 微软手写识别模块sdk及delphi接口例子
- delphi android 中 Toast 的实现(老外写的UNIT)
unit Android.JNI.Toast; // Java bridge class imported by hand by Brian Long (http://blong.com)interf ...
- jQuery Validate 验证,校验规则写在控件中的具体例子
将校验规则写到控件中 <script src="../js/jquery.js" type="text/javascript"></scrip ...
- 转 Activity的四种LaunchMode(写的真心不错,建议大家都看看)
我们今天要讲的是Activity的四种launchMode. launchMode在多个Activity跳转的过程中扮演着重要的角色,它可以决定是否生成新的Activity实例,是否重用已存在的 ...
- 写于疫情期间的一个plantUML例子
@startuml 这几天的正经事 start repeat if(思维清晰) then (yes) :刷题; else (no) if(想写程序) then (yes) :调项目; else (no ...
- 写的一个Sass 和Compass的例子
/*1.打开项目根目录下的 config.rb 文件 2.搜索 line_comments 关键词,默认应该是 # line_comments = false 3.去掉前面的 #,保存 config. ...
- 《分布式对象存储》作者手把手教你写 GO 语言单元测试!
第一部分:如何写Go语言单元测试 Go语言内建了单元测试(Unit Test)框架.这是为了从语言层面规范写UT的方式. Go语言的命名规则会将以_test.go结尾的go文件视作单元测试代码. 当我 ...
- 数百个 HTML5 例子学习 HT 图形组件 – 拓扑图篇
HT 是啥:Everything you need to create cutting-edge 2D and 3D visualization. 这口号是当年心目中的产品方向,接着就朝这个方向慢慢打 ...
随机推荐
- 关于C语言的问卷调查(作业三)
1.你对自己的未来有什么规划?做了哪些准备? 答:我对我未来的规划就是希望能够学有所用,将来可以从事有关IT方面的,跟自己的专业对口.为此现在我需要多看一些和这个专业有关的书籍,自学一些知识,多些一些 ...
- CSS3的透明度使用
大家在敲代码的时候总会遇见一个问题.就是透明度opacity 会导致整个元素内全部都会改变,通常的方法是在同级元素后面再加上一个元素标签,但是现在有CSS3 ,我们完全不用这么做了.看代码 <! ...
- 各种url编码
URLENCODE和URLDECODE是比较常用的URL参数转换方法,为以后使用方便,自己归类一下. 一.JavaScript: 编码:encodeURIComponent(URIString) ...
- Javascript闭包(狗血剧情,通俗易懂)
我们先来看一个闭包的函数: function a() { var i = 0; function b() { alert(++i); } return b; } var c = a(); c(); c ...
- C#导入Excel遇到数字字母混合列数据丢失解决
错误重现: ----------------------------------------------------------------------- 在导入Excel读取数据时,其中的一个字段保 ...
- simple_html_dom配合snoopy使用
https://github.com/samacs/simple_html_dom Snoopy的特点是“大”和“全”,一个fetch什么都采到了,可以作为采集的第一步.接下来就需要用simple_h ...
- 关于容器为NavigationControlle时,view的起始位置的问题
在iOS 7中,苹果引入了一个新的属性“EdgesForExtendedLayout”,默认值为UIRectEdgeAll,默认的布局将从navigationbar的顶部开始,这就是为什么所有元素都往 ...
- 输入两个正整数m和n,求其最大公约数和最小公倍数
public static void main(String[] args){ Scanner sc = new Scanner (System.in); int a,b; System.out ...
- window 下如何安装ghost博客
1.安装nodejs # Node v0.12.x and v4.2+ LTS - supported 我本地安装的是4.2 安装其他版本可能提示系统不兼容 2.安装mysql 3.安装bower 4 ...
- 关于HTML标签那些事儿
关于html相信对于每一个互联网从业者来说实在熟悉不过的一个名词,特别是web前端工程师来说更是基础中的基础.html是hyper text markup language的首字母缩写,翻译过来就是超 ...