最近翻了下写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. Httpclient请求数据

    package com.baidu.myutils; import java.io.IOException; import org.apache.http.HttpEntity; import org ...

  2. java语言程序设计(一)-2

    (一)jdk安装及环境变量配置 1.jdk下载 下载地址http://www.oracle.com/technetwork/java/javase/downloads/index.html,下载SE标 ...

  3. Monkey基本使用流程及测试报告分析

    前一篇文章介绍了Monkey的API函数内容,这篇文章介绍windows环境下Monkey的基本使用方法. 由于博客园年底才能完成对markdown解析的升级,可移步我的个人博客查看此文,已获得更好的 ...

  4. JSP 新闻发布会

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

  5. android自定义按键

    android自带菜单键.返回键.搜索键的重写 转自:http://blog.sina.com.cn/s/blog_7cb9b3b801015yk8.html   返回键 public void on ...

  6. Install and set JAVA home on MAC OS with commandline

    最近需要在MAC上做一些测试,由于测试机没有安装Java,只能自己安装,由于不能通过图形化界面访问测试机,只能通过命令行的形式来安装JAVA. 1. Download the jre/jdk inst ...

  7. Unity jounal 2016-3-3

    1. Project organization: 2.prefab Important part of the project, which seperate and organize the scr ...

  8. Cosh.3

    查壳.没有 拖 OD 查找字符串 找到有用的东西   顺线往上看       找到  大概算入口处  下断 就从这里开始  单步下去吧 name的变幻 Serial的变幻 直接翻译出来了   继续看看 ...

  9. php 使用 curl 发送 post 数据

    作为第三方开发商,经常会需要调用平台接口,远程调用,就要用到curl,其实质就是叫调用的方法与用到的参数以http post的方式发送至平台服务器. 简单的例子: $url = 'http://'; ...

  10. C# 字符编码类Encoding

    在网络通信中,很多情况下都是将字符信息转成字节序列进行传输.将字符序列转为字节序列的过程称为编码.当这些字节传送到接收方,接收方需要逆向将字节序列转为字符序列.这个过程就是解码. 常见编码有ASCII ...