写好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. 这口号是当年心目中的产品方向,接着就朝这个方向慢慢打 ...
随机推荐
- JS 数字,金额 用逗号 隔开(数字格式化)
<script> function fmoney(s,n) { n = n > 0 && n <= 20 ? n : 2; s = parseFloat((s ...
- c语言操作一维数组-3
C语言选择题#includemain(){double a[15],k;k=fun(a);} 则以下选项中错误的fun函数首部是 ( D)A.double fun(double a[15]) B.do ...
- eap-md5
eap-md5 文件路径 用途 示例 备注 #gedit /usr/local/etc/raddb/sites-available/default #gedit /usr/local/et ...
- 第九章 硬件抽象层:HAL
这一章介绍HAL,全称为Hardware Abstract Layer,即硬件抽象层,它是建立在Linux驱动之上的一套程序库,程序库并不属于Linux内核,而是属于Linux内核层之上的应用层.为A ...
- Hello, RealSense!
这是kinect for windows: 这是华硕 xtion pro: 这是Intel® RealSense™: 几经周折,终于买到了,99美元套件+25美元运费,正在旅途中.
- Unity Ugui射线坐标转换总结
世界空间中的点坐标转换到屏幕坐标: screenPos = RectTransformUtility.WorldToScreenPoint(cam, worldPos.transform.positi ...
- storm 源码笔记
(reify DistributedRPC$Iface (^String execute [this ^String function ^String args] (log-debug " ...
- linux中模块的构建,传参,和printk函数的简单使用
静态编译,动态加载应用想访问内核需要通过系统调用 驱动:1.模块(打包,加入内核)2.内核机制3.操作硬件 在Kconfig里面配置menuconfig的时候,不同的类型会在图形化界面的终端显示不用的 ...
- 字符数组和string判断是否为空行 NULL和0 namespace变量需要自己进行初始化
string 可以这样判断空行input !="" 字符数组可以通过判断第一个元素是否为空字符'\0',是的话为空行arrar[0]=='\0':或者用长度strlen(char ...
- HDU5950(矩阵快速幂)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5950 题意:f(n) = f(n-1) + 2*f(n-2) + n^4,f(1) = a , f(2 ...