#!/usr/bin/env python
# encoding: utf-8 import unittest """
the simplyest way to test return value
No needs to use stub
"""
class LogAnalyzer_0(object):
def IsValidLogFileName(self, fileName):
return str(fileName).endswith('.sln')
"""
However somethimes we have to rely on the extenal class or method
that we cannot control on it or it has not been finished yet
This is when we need stub to help us. eg, draw_from_weighted_range() and randrange(), interacting with filesystem.
Fakes here include stub (assert on CUT) and mock (assert on Fake) we talk about stub and mock in later posts.
Say our IsValidLogFileName() method needs read through the config file and return true if extension is supported in config file, There two big types to inject fakes into MUT(Method Under Test):
1.Test are performed on the MUT itself (eg. assert(mut.dosomething(),true)
1.1 Abstracting concrete objects into interfaces or delegates
How: Extract an interface to allow replacing or extending underlying impl
1.2 Refactoring to allow injection of faked implementations of those delegates or interface.
How:
1.2.1.Inject stub in code under test using factory design (layer of indirection 2 faking a member in factory class)
the difference is that the object initiating the stub request is the code under test.
the fake instances was set by code external to the code under test before the test started in the below.
A test configures the factory class to re turn a stub object. The class usess the factory class to get the
stub instance, which in production code would return an object that is not a stub
Preferred to using this layer
1.2.2 Injection of a stub in test code (layer of indiretion 1 faking a member in class under test)
1.2.2.1 Inject stub via ctor (cumbersome whenyou have many dependencies)
1.2.2.2 Inject stub via setter/getter
This is much simpler than ctor injection as each test can set only the dependencies
that it needs to get the test underway;
Use this when you want to signify that the dependency is optional or the dependency has
a default instance created that does not create any problems; 1.2.4.Inject stub impl via parameter
2.Test are performed on the class that inhetites from MUT (eg. assert(mut_child.dosomething(),true)
It is also known as Extract and override, which is is good to for sumulating inputs into your code under test
(in other words, return values from dependency). but it is cumbersome when you want t verify and check interactions
that are coming out of the code under test int othe dependency (in other words, it is good to play stub but very bad to play mock) 2.1 use local virtual factory method to get instance of stub
The time not to use this is there is an interface ready to fake or there is already a place that seam can be injected.
2.2 use extract and override to return a logical result instead of calling an actual denpendency
This uses a simple faked result instead of a stub
Much easier than 2.1 preferred to use
""" # Refered to "1.1 Abstracting concrete objects into interfaces or delegates"
class ExtensionMgr_AbstractedInterface(object):
def IsValid(self, filename): # should be overwriten by child
pass class FileExtensionMgr_ConcreteImpl(ExtensionMgr_AbstractedInterface):
def IsValid(self, filename):
return str(filename).endswith('.sln') # Stubs
class ExtendMgrStub(ExtensionMgr_AbstractedInterface):
def __init__(self):
self.mWillBeValid = False
return ExtensionMgr_AbstractedInterface.__init__(self) def IsValid(self, filename):
return self.mWillBeValid class ExtendMgrStub_WithoutIngeritingFrom_ExtensionMgr_AbstractedInterface(object):
def __init__(self):
self.mWillBeValid = False def IsValid(self, filename):
return self.mWillBeValid # Refered to 1.2.2.1 Inject stub impl via ctor (cumbersome whenyou have many dependencies)
class LogAnalyzer_StubInjectedViaCtor(object):
def __init__(self, iExtensionMgr):
self.mIExtensionMgr = iExtensionMgr def IsValidLogFileName(self, fileName):
self.mIExtensionMgr.IsValid(fileName) # Refered to "1.2.2.2 Inject stub impl via a setter and ggeter"
class LogAnalyzer_StubInjectedViaPropertySetter(object):
def __init__(self):
self.mIExtensionMgr = FileExtensionMgr_ConcreteImpl() def IsValidLogFileName(self, fileName):
self.mIExtensionMgr.IsValid(fileName) def SetIExtensionMgr(self, ext):
self.mIExtensionMgr = ext def GetIExtensionMgr(self):
return self.mIExtensionMgr # Refered to "1.2.1.Inject stub in code under test using factory design"
class ExtensionMgrFactory(object):
iExtMgr = None @staticmethod
def Create():
# define factory that can use and return custom manager instance
if ExtensionMgrFactory.iExtMgr is None:
ExtensionMgrFactory.iExtMgr = FileExtensionMgr_ConcreteImpl()
else:
return ExtensionMgrFactory.iExtMgr @staticmethod
def SetExtMgr(extmgr):
ExtensionMgrFactory.iExtMgr = extmgr class LogAnalyzer_StubInjectedViaFactory(object):
def __init__(self):
self.mIExtensionMgr = ExtensionMgrFactory.Create() def IsValidLogFileName(self, fileName):
self.mIExtensionMgr.IsValid(fileName) #Referred to "2.1 use local virtual factory method to get instance of stub"
class LogAnalyzer_StubInjectedViaLocalFactoryMethod(object):
def IsValidLogFileName(self, fileName):
self.GetMgr().IsValid(fileName)
def GetMgr(self):
return FileExtensionMgr_ConcreteImpl() class TestableLogAnalyzer_ReturnStub(LogAnalyzer_StubInjectedViaLocalFactoryMethod):
def __init__(self, iExtensionMgr):
self.mIExtensionMgr = iExtensionMgr
def GetMgr(self):
return self.mIExtensionMgr #Referred to "2.2 use extract and override to return a logical result instead of calling an actual denpendency"
class LogAnalyzer_OverrideMethodReturnsResult(object):
def __init__(self):
self.mIExtensionMgr = FileExtensionMgr_ConcreteImpl()
def IsValidLogFileName(self, fileName):
self.IsValidExtension(fileName)
def IsValidExtension(self,filename):
return self.mIExtensionMgr.IsValid(filename) class TestableLogAnalyzer_OverrideMethodReturnsResult(LogAnalyzer_OverrideMethodReturnsResult):
def __init__(self, is_valid_entension):
self.is_valid_entension = is_valid_entension
def IsValidExtension(self,filename):
return self.is_valid_entension # cut means by class under test mut means by method under test
class LogAnalyzerTestCase(unittest.TestCase): # No stub used just simply perform the test
def test_IsValidLogFileName_BadExtension_ReturnFalse_NoStub(self):
logAnalyzer0 = LogAnalyzer_0()
ret = logAnalyzer0.IsValidLogFileName('fn1.sl')
self.assertFalse(ret) # StubIjectedViaCtor
def test_IsValidLogFileName_BadExtension_ReturnFalse_StubIjectedViaCtor(self):
ext = ExtendMgrStub()
ext.mWillBeValid = False
logAnalyzer = LogAnalyzer_StubInjectedViaCtor(ext)
ret = logAnalyzer.IsValidLogFileName('fn1.sl')
self.assertFalse(ret) # StubIjectedViaCtor
# This is what I wrote because python is weak-type language
# so it can still work without using inheratance
def test_IsValidLogFileName_BadExtension_ReturnFalse_StubIjectedViaCtor_WithoutInhertingFrom_ExtensionMgr_AbstractedInterface(self):
ext = ExtendMgrStub_WithoutIngeritingFrom_ExtensionMgr_AbstractedInterface()
ext.mWillBeValid = False logAnalyzer = LogAnalyzer_StubInjectedViaCtor(ext)
ret = logAnalyzer.IsValidLogFileName('fn1.sl') self.assertFalse(ret) # StubInjectedViaPropertySetter
def test_IsValidLogFileName_BadExtension_ReturnFalse_StubInjectedViaPropertySetter(self):
ext = ExtendMgrStub()
ext.mWillBeValid = False logAnalyzer = LogAnalyzer_StubInjectedViaPropertySetter()
logAnalyzer.SetIExtensionMgr(ext)
ret = logAnalyzer.IsValidLogFileName('fn1.sl') self.assertFalse(ret) # StubIjectedViaFactory
def test_IsValidLogFileName_BadExtension_ReturnFalse_4_StubIjectedViaFactory(self):
ext = ExtendMgrStub()
ext.mWillBeValid = False
ExtensionMgrFactory.SetExtMgr(ext) logAnalyzer = LogAnalyzer_StubInjectedViaFactory()
ret = logAnalyzer.IsValidLogFileName('fn1.sl') self.assertFalse(ret) # OverrideMethodReturnsResult
def test_IsValidLogFileName_BadExtension_ReturnFalse_4_OverrideMethodReturnsResult(self):
is_valid_extension = False testableLogAnalyzer = TestableLogAnalyzer_OverrideMethodReturnsResult(is_valid_extension)
ret = testableLogAnalyzer.IsValidLogFileName('fnl.sl') self.assertFalse(ret) if __name__ == '__main__':
unittest.main()

Art of Unit Test (1) - Breaking Dependency的更多相关文章

  1. The Art of Unit Testing With Examples in .NET

    The Art of Unit Testing With Examples in .NET

  2. C# Note37: Writing unit tests with use of mocking

    前言 What's mocking and its benefits Mocking is an integral part of unit testing. Although you can run ...

  3. Unit Testing with NSubstitute

    These are the contents of my training session about unit testing, and also have some introductions a ...

  4. What's the difference between a stub and mock?

    I believe the biggest distinction is that a stub you have already written with predetermined behavio ...

  5. Adaptive Code Via C#读书笔记

    原书链接: http://www.amazon.com/Adaptive-Code-via-principles-Developer-ebook/dp/B00OCLLYTY/ref=dp_kinw_s ...

  6. Nikola的5项依赖注入法则

    本篇文章来自对 Nikola Malovic 博客文章 <Inversion Of Control, Single Responsibility Principle and Nikola’s l ...

  7. (C#)程序员必读的一些书籍

    前言 ·貌似公司里很著名的一句话,在这里套用过来了,WP研发工程师,首先是WPF/SL研发工程师,WPF/SL研发工程师首先是是个C#研发工程师,C#研发工程师首先Windows研发工程师.Windo ...

  8. Snoop resynchronization mechanism to preserve read ordering

    A processor employing a post-cache (LS2) buffer. Loads are stored into the LS2buffer after probing t ...

  9. Method and system for early speculative store-load bypass

    In an embodiment, the present invention describes a method and apparatus for detecting RAW condition ...

随机推荐

  1. MySQL导入sql 文件的5大步骤

    http://database.51cto.com/art/201005/200739.htm 以下的文章主要介绍的是MySQL导入sql 文件,即MySQL数据库导入导出sql 文件的实际操作步骤, ...

  2. RDLC报表系列(四) 矩阵

    继续接上一篇的内容,本文主要是讲矩阵的内容 用到的数据源如下: DataTable dt = new DataTable(); dt.Columns.Add("FiscalYear" ...

  3. Spring-----配置复杂对象

    转载自:http://blog.csdn.net/hekewangzi/article/details/51713037

  4. IE9下Ajax缓存问题

    使用jQuery的getJSON从后台定时获取数据并刷新界面,使用以下方法时,在Chrome,Firefox下没问题,但在IE9下却无法刷新数据 $.getJSON(webApp + "/G ...

  5. Android L 之 RecyclerView 、CardView 、Palette

    转: http://blog.csdn.net/xyz_lmn/article/details/38735117 <Material Design>提到,Android L版本中新增了Re ...

  6. TensorFlow 深度学习笔记 逻辑回归 实践篇

    Practical Aspects of Learning 转载请注明作者:梦里风林 Github工程地址:https://github.com/ahangchen/GDLnotes 欢迎star,有 ...

  7. Http Analyzer 数据抓包

    一.工具简介 这是一款实时分析 HTTP/HTTPS 数据流的工具.它可以实时捕捉HTTP/HTTPS 协议数据,可以显示许多信息(包括:文件头.内容.Cookie.查询字符窜.提交的数据.重定向的U ...

  8. 客户端持久化解决方案: Web SQL

    客户端持久化解决方案: Web SQL Web SQL 提供了一组使用 SQL 操作客户端数据库的 APIs, 不是 HTML5 规范的一部分,是一个独立的规范. 核心方法 openDatabase: ...

  9. Java书籍推荐

    Java书籍推荐 转自:http://www.cnblogs.com/exclm/archive/2009/01/03/1367597.html 一.入门 <Java 2从入门到精通>- ...

  10. libiconv_百度百科

    libiconv_百度百科   由于历史原因,国际化的文字常常由于语言或者国家的原因使用不同的编码.目录     1libiconv历史简介     2libiconv编码简介     3libico ...