#!/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. MVC+simpleinjector 简单使用

    一.首先添加NuGet包如下图

  2. dede 设置为全动态浏览

    将织梦所有栏目设置为“使用动态页”,可以再建立栏目时选择“使用动态页”:也可以执行下面的SQL语句.update dede_arctype set isdefault=-1 将网站所有文档都设置为“仅 ...

  3. [Linked List]Remove Duplicates from Sorted List

    Total Accepted: 90247 Total Submissions: 254602 Difficulty: Easy Given a sorted linked list, delete ...

  4. 内存泄漏工具VLD1.0_要点分析

    0X01 关闭FPO优化 // Frame pointer omission (FPO) optimization should be turned off for this // entire fi ...

  5. 提高php代码质量 36计

    1.不要使用相对路径 常常会看到: ? 1 require_once('../../lib/some_class.php'); 该方法有很多缺点: 它首先查找指定的php包含路径, 然后查找当前目录. ...

  6. Android EditText屏蔽默认长按粘贴复制事件

    et.setCustomSelectionActionModeCallback(new ActionMode.Callback()); 添加全部的方法即可,不需要任何改动.

  7. 关于Git和Github

    英文原文:Ten Things You Didn't Know Git And GitHub Could Do Git 和 GitHub 都是非常强大的工具.即使你已经使用他们很长时间,你也很有可能不 ...

  8. Django模板-在视图中使用模板

    之前我们已经有了自己的视图mysite.views.py中,应该是这样子的 from django.http import HttpResponse import datetime def curre ...

  9. javascript二级联动

    二级联动在一般的网页中随处可见,一般是地址,比如点击浙江省,随后出现的是杭州市,嘉兴市:点击北京省出现的是朝阳,海淀,而不是出现杭州,嘉兴. 要想实现这个步骤,就要用到javascript来实现.其中 ...

  10. check单选框多个全选与取消全选

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...