最近翻了下写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的建议和例子的更多相关文章

  1. 写几个简单用artTemplate的例子

    写几个简单的artTemplate的例子,很多框架都有自己的模板(template),没得时候,可以利用artTemplate.js完成 html文件是: <!DOCTYPE html> ...

  2. 微软手写识别模块sdk及delphi接口例子

    http://download.csdn.net/download/coolstar1204/2008061 微软手写识别模块sdk及delphi接口例子

  3. delphi android 中 Toast 的实现(老外写的UNIT)

    unit Android.JNI.Toast; // Java bridge class imported by hand by Brian Long (http://blong.com)interf ...

  4. jQuery Validate 验证,校验规则写在控件中的具体例子

    将校验规则写到控件中 <script src="../js/jquery.js" type="text/javascript"></scrip ...

  5. 转 Activity的四种LaunchMode(写的真心不错,建议大家都看看)

      我们今天要讲的是Activity的四种launchMode. launchMode在多个Activity跳转的过程中扮演着重要的角色,它可以决定是否生成新的Activity实例,是否重用已存在的 ...

  6. 写于疫情期间的一个plantUML例子

    @startuml 这几天的正经事 start repeat if(思维清晰) then (yes) :刷题; else (no) if(想写程序) then (yes) :调项目; else (no ...

  7. 写的一个Sass 和Compass的例子

    /*1.打开项目根目录下的 config.rb 文件 2.搜索 line_comments 关键词,默认应该是 # line_comments = false 3.去掉前面的 #,保存 config. ...

  8. 《分布式对象存储》作者手把手教你写 GO 语言单元测试!

    第一部分:如何写Go语言单元测试 Go语言内建了单元测试(Unit Test)框架.这是为了从语言层面规范写UT的方式. Go语言的命名规则会将以_test.go结尾的go文件视作单元测试代码. 当我 ...

  9. 数百个 HTML5 例子学习 HT 图形组件 – 拓扑图篇

    HT 是啥:Everything you need to create cutting-edge 2D and 3D visualization. 这口号是当年心目中的产品方向,接着就朝这个方向慢慢打 ...

随机推荐

  1. 【转】修改LINUX时间

    命令格式为: date -s 时间字符串 例如只修改系统的日期,不修改时间(时分秒) date -s 2012-08-02 或只修改时间不修改日期 date -s 10:08:00 当然也可以同时修改 ...

  2. 自定义javascript log方法

    /** * 类似chrome,firefox的console对象 * 但是在IE等不支持console的浏览器不会报错 * 理论上浏览器支持的console的方法都支持,比如谷歌的 * assert, ...

  3. jquery如何根据text选择option

    百度出来的代码都是这样的: $('#test option[text="b"]').attr("selected",true); 或 $('#test').fi ...

  4. StoryBoard解惑

    可以把StoryBoard看做是一组viewController对应的xib,以及它们之间的转换方式的集合.在StoryBoard中不仅可以看到 每个ViewController的布局样式,也可以明确 ...

  5. js回车动态添加表格,右键动态删除表格行

    <script type="text/javascript" language="javascript">//屏蔽浏览器右键function sto ...

  6. JSP 新闻发布会

    ---恢复内容开始--- 首先 新闻发布会结合了JSP里的Servlet和request对象,response对象还有使用session对象和cookie对象跟踪用户信息等等..... 列表 登陆 这 ...

  7. unix下输出重定向

    > 为重定向符号 >> 重定向不覆盖原文件内容 example: 1. 标准输出重定向 echo "123" > /home/123.txt ---- 标准 ...

  8. Oracle中的MD5加密详解

    一.技术点 1. DBMS_OBFUSCATION_TOOLKIT.MD5 DBMS_OBFUSCATION_TOOLKIT.MD5是MD5编码的数据包函数,但偶在使用select DBMS_OBFU ...

  9. vue吃进去的object已经变了样,不在是原来的!

    直接上代码: class data { public list:number[]; constructor() { this.list=[0,0,0]; } } class methods exten ...

  10. 长时间停留在calculating requirements and dependencies 的解决方案

    如果Eclipse花费了很长的时间calculating requirements and dependencies(计算需求和依赖性 ) 这个问题通常就是在点击安装之后显示“Calculating ...