写好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. 这口号是当年心目中的产品方向,接着就朝这个方向慢慢打 ...
随机推荐
- 颜色代码表#FFFFFF #FF0000 #00FF00 #FF00FF (2015-07-21 10:39)转载
▼标签: 颜色代码表 白色 ffffff 红色 ff0000 黑色 000000 it 分类: hht1 白色 #FFFFFF 2 红色 #FF0000 3 绿色 #00FF00 4 蓝色 # ...
- Android四大基本组件介绍与生命周期
Android四大基本组件介绍与生命周期 Android四大基本组件分别是Activity,Service服务,Content Provider内容提供者,BroadcastReceiver广播接收器 ...
- entity framework 新手入门篇(3)-entity framework实现orderby,count,groupby,like,in,分页等
前面我们已经学习了entityframework的基本的增删改查,今天,我们将在EF中实现一些更加贴近于实际功能的SQL方法. 承接上面的部分,我们有一个叫做House的数据库,其中包含house表和 ...
- think in java学习笔记
java作用域关键字: public:任何人均可使用 private:除您自己.类型的创建者以及那个类型的内部函数成员,其他任何人都不能访问 protected:只有继承的类可以访问 friendly ...
- JavaScript数组模拟栈和队列
*栈和队列:js中没有真正的栈和队列的类型 一切都是用数组对象模拟的 栈:只能从一端进出的数组,另一端封闭 FILO 何时使用:今后只要仅希望数组只能从一端进 ...
- gantt甘特图的制作过程
甘特图主要是用来做项目管理的,可以清楚的看到任务间的逻辑关系,任务与时间关系和任务间并行关系. 在甘特图中,横轴方向表示时间,纵轴方向并列着活动列表.图表内可以用线条.数字.文字代号等来表示计划(实际 ...
- Visual C# 代码段
代码段是现成的代码段,您可以快速将其插入到您的代码中. 例如,for 代码段创建一个空的 for 循环. 有些代码段为外侧代码段,这些代码段允许您先选择代码行,然后选择要并入选定代码行的代码段. 例如 ...
- 学习SVG系列(4):SVG滤镜效果
注意:Internet Explorer和Safari不支持SVG滤镜 <defs>.<filter> 所有互联网的SVG滤镜定义在<defs>元素中,<fi ...
- Unity3D 处理Label的颜色代码
UILabel m_name = transform.Find("Name").GetComponent<UILabel>(); m_name.text = GetNa ...
- core Bluetooth(蓝牙4.0)
蓝牙4.0以低功耗著称,一般也叫BLE(Bluetooth Low Energy). 目前主要应用的场景有:智能家居.运动手环和室内导航等. 利用core Bluetooth框架可以实现苹果设备与第三 ...