SlideShare a Scribd company logo
1 of 28
Isolating Dependencies with Microsoft Fakes
   Introducing Fakes
   The Basics
   Using Stubs
   Using Shims
   Advanced Configuration
   Final Notes
   Resources
   What is it?
   Where did it come from?
   Inheritance based
   Used when testing a defined contract
Let me start by saying Shims are evil. But they are
evil by design. They let you do things you otherwise
couldn’t do, which is very powerful. They let you do
things you might not want to do, and might know
you shouldn’t do, but because of the real world of
software, you have to do.

                                     Peter Provost
                           Program Manager Lead
                           Visual Studio ALM Tools
   Use a profiler to rewrite existing method
    bodies
   Detour virtually any .NET method
   Performance issues due to the profiler
   No additional installation required
   Isolation type generation driven by .fakes file
   Microsoft.QualityTools.Testing.Fakes
    assembly/namespace
   Delegates are used to provide the faked
    functionality
   Custom delegate types including support for
    out and ref parameters
   Static class:
     Microsoft.QualityTools.Testing.Fakes.FakesDelegates
   Action            Func
   OutAction         OutFunc
   OutOutAction      OutOutFunc
   RefAction         RefFunc
   RefRefAction      RefRefFunc
   Isolation types are placed in a .Fakes namespace
   Stub types are prefixed with “Stub”
   Shim types are prefixed with “Shim”
   Method parameter types are appended to the
    method name
   “Get” or “Set” is appended to property names
     Setters also include parameter type names (like
      methods)
 Generic type arguments are appended to the
  method name for generic methods
 Constructors have parameter type names
  appended to “Constructor”
   Assign a delegate to the field that
    corresponds to the member being isolated
   Same process as methods
   Get and Set can be assigned individually
   AttachBackingFieldTo[PropertyName]
    convenience method
   The framework generates a public method to
    invoke events
     [EventName]Event
   Allow calling the base implementation when
    a delegate is not set for a member
   Control what happens when a delegate has
    not been provided for a member
   Set through the InstanceBehavior property
   Shim properties for static members are static
    on the shim type
   Static AllInstances property for applying
    delegates to all instances of the shim type
   Instance properties for applying delegates to
    a single instance
   ShimsContext
     Sets up the shim under the IntelliTrace profiler
     ShimsContext.Create()
   Events don’t have a method to invoke
     Properties representing the Add and Remove
     operations are provided instead
   Base type members aren’t directly accessible
   Static constructors are “shimmable”
   Bind method for each interface implemented
    by the shimmed type
   Behaviors are controlled by ShimBehaviors
   Controlling Type Generation
   Strong Name Signing
   Generating the isolation types is expensive
    and will extend build time
   Configure through the .fakes file
   Filtering
Attribute                           Type   Stubs?   Shims?
AbstractClasses             Boolean               

FullName                    String                        

Interfaces                  Boolean               

Namespace                   String                        

Obsolete*                   Boolean                       

TypeName                    String                        




     * Applies only to Remove elements
   ! forces an exact, case sensitive match
   * matches the beginning of the string
   Fakes assemblies will be signed with the
    same key as the underlying assembly unless
    otherwise specified
   Compilation element’s KeyFile attribute in
    .fakes file
   Beware the Docs!
   Notable Changes from Moles
 Configured through .fakes file rather than .moles
 Namespace and assembly are .Fakes rather than
  .moles
 Mole types are now shim types
 Stub prefix is “Stub” rather than “S”
 Shim prefix is “Shim” rather than “M”
 ShimsContext replaces HostTypeAttribute
 Automatic properties can be isolated!
 Moles allowed for erasing static constructors and
  finalizers. Fakes allows shimming static constructors
  but has no support for finalizers
 Moles could control the bitness of the profiler
 “classes” filter attribute was removed
   Isolating Unit Test Methods with Microsoft
    Fakes
    http://bit.ly/KYMkyX

   Moles Isolation Framework for .NET
    http://bit.ly/LebqZ2

   Going Underground: Microsoft Moles
    http://bit.ly/y66D5C

More Related Content

Similar to Faking it

ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
Saurabh Narula
 
NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
Niall Merrigan
 
Using SP Metal for faster share point development
Using SP Metal for faster share point developmentUsing SP Metal for faster share point development
Using SP Metal for faster share point development
Pranav Sharma
 

Similar to Faking it (20)

Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design Guidelines
 
Using SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint developmentUsing SPMetal for faster SharePoint development
Using SPMetal for faster SharePoint development
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
 
C# 6.0 - DotNetNotts
C# 6.0 - DotNetNottsC# 6.0 - DotNetNotts
C# 6.0 - DotNetNotts
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
C# - Igor Ralić
 
NNUG Certification Presentation
NNUG Certification PresentationNNUG Certification Presentation
NNUG Certification Presentation
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Robotlegs AS3 from Flash and the City 2010
Robotlegs AS3 from Flash and the City 2010Robotlegs AS3 from Flash and the City 2010
Robotlegs AS3 from Flash and the City 2010
 
Building Content Types with Dexterity
Building Content Types with DexterityBuilding Content Types with Dexterity
Building Content Types with Dexterity
 
A lab around the principles and practices for writing maintainable code
A lab around the principles and practices for writing maintainable codeA lab around the principles and practices for writing maintainable code
A lab around the principles and practices for writing maintainable code
 
Java basics
Java basicsJava basics
Java basics
 
Using SP Metal for faster share point development
Using SP Metal for faster share point developmentUsing SP Metal for faster share point development
Using SP Metal for faster share point development
 
Serialization in .NET
Serialization in .NETSerialization in .NET
Serialization in .NET
 
Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++Static and Dynamic polymorphism in C++
Static and Dynamic polymorphism in C++
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
C sharp
C sharpC sharp
C sharp
 
Angular Best Practices - Perfomatix
Angular Best Practices - PerfomatixAngular Best Practices - Perfomatix
Angular Best Practices - Perfomatix
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Back-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real WorldBack-2-Basics: .NET Coding Standards For The Real World
Back-2-Basics: .NET Coding Standards For The Real World
 
Spring training
Spring trainingSpring training
Spring training
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Faking it

  • 1. Isolating Dependencies with Microsoft Fakes
  • 2. Introducing Fakes  The Basics  Using Stubs  Using Shims  Advanced Configuration  Final Notes  Resources
  • 3. What is it?  Where did it come from?
  • 4. Inheritance based  Used when testing a defined contract
  • 5. Let me start by saying Shims are evil. But they are evil by design. They let you do things you otherwise couldn’t do, which is very powerful. They let you do things you might not want to do, and might know you shouldn’t do, but because of the real world of software, you have to do. Peter Provost Program Manager Lead Visual Studio ALM Tools
  • 6. Use a profiler to rewrite existing method bodies  Detour virtually any .NET method  Performance issues due to the profiler
  • 7. No additional installation required  Isolation type generation driven by .fakes file  Microsoft.QualityTools.Testing.Fakes assembly/namespace
  • 8. Delegates are used to provide the faked functionality  Custom delegate types including support for out and ref parameters  Static class:  Microsoft.QualityTools.Testing.Fakes.FakesDelegates
  • 9. Action  Func  OutAction  OutFunc  OutOutAction  OutOutFunc  RefAction  RefFunc  RefRefAction  RefRefFunc
  • 10. Isolation types are placed in a .Fakes namespace  Stub types are prefixed with “Stub”  Shim types are prefixed with “Shim”  Method parameter types are appended to the method name  “Get” or “Set” is appended to property names  Setters also include parameter type names (like methods)  Generic type arguments are appended to the method name for generic methods  Constructors have parameter type names appended to “Constructor”
  • 11. Assign a delegate to the field that corresponds to the member being isolated
  • 12. Same process as methods  Get and Set can be assigned individually  AttachBackingFieldTo[PropertyName] convenience method
  • 13. The framework generates a public method to invoke events  [EventName]Event
  • 14. Allow calling the base implementation when a delegate is not set for a member
  • 15. Control what happens when a delegate has not been provided for a member  Set through the InstanceBehavior property
  • 16.
  • 17. Shim properties for static members are static on the shim type  Static AllInstances property for applying delegates to all instances of the shim type  Instance properties for applying delegates to a single instance
  • 18. ShimsContext  Sets up the shim under the IntelliTrace profiler  ShimsContext.Create()
  • 19. Events don’t have a method to invoke  Properties representing the Add and Remove operations are provided instead  Base type members aren’t directly accessible  Static constructors are “shimmable”  Bind method for each interface implemented by the shimmed type  Behaviors are controlled by ShimBehaviors
  • 20.
  • 21. Controlling Type Generation  Strong Name Signing
  • 22. Generating the isolation types is expensive and will extend build time  Configure through the .fakes file  Filtering
  • 23. Attribute Type Stubs? Shims? AbstractClasses Boolean  FullName String   Interfaces Boolean  Namespace String   Obsolete* Boolean   TypeName String   * Applies only to Remove elements
  • 24. ! forces an exact, case sensitive match  * matches the beginning of the string
  • 25. Fakes assemblies will be signed with the same key as the underlying assembly unless otherwise specified  Compilation element’s KeyFile attribute in .fakes file
  • 26. Beware the Docs!  Notable Changes from Moles
  • 27.  Configured through .fakes file rather than .moles  Namespace and assembly are .Fakes rather than .moles  Mole types are now shim types  Stub prefix is “Stub” rather than “S”  Shim prefix is “Shim” rather than “M”  ShimsContext replaces HostTypeAttribute  Automatic properties can be isolated!  Moles allowed for erasing static constructors and finalizers. Fakes allows shimming static constructors but has no support for finalizers  Moles could control the bitness of the profiler  “classes” filter attribute was removed
  • 28. Isolating Unit Test Methods with Microsoft Fakes http://bit.ly/KYMkyX  Moles Isolation Framework for .NET http://bit.ly/LebqZ2  Going Underground: Microsoft Moles http://bit.ly/y66D5C

Editor's Notes

  1. OriginsPex & Moles from Microsoft ResearchPex dates back to at least 2007Moles dates back to at least 2009I didn’t learn about them until late 2011Tell GiveCamp storyProductization of Moles in VS2012 (Premium & Ultimate or just Ultimate?)Docs say Premium & UltimateA Connect post says Ultimate onlyIsolation FrameworkStubs and ShimsGenerated according to a .Fakes fileNo validation off its ownMoq has .Verify methodsUse whichever test framework you wantVS2012 allows running tests with any framework that has the appropriate adapterGet from extension managerMore in common with Telerik’sJustMock than anything else
  2. InterfacesVirtual members of non-sealed classesNative implicit substitutionStubbed concrete classes derive directly from the stubbed typeStubbed interfaces derive from StubBase<T> and implement the stubbed interface
  3. No support for interfaces or abstract members (no bodies to rewrite)Favor stubs whenever possibleRequired for:Private membersStatic membersSealed types3rd Party libraries w/o a testable APIProvide an implicit conversion operator to the underlying typeAlso have a .Instance property
  4. .fakes fileXML File (with an installed schema!)Intellisense!Add by right-clicking a reference in the project where your tests live and selecting “Add Fakes Assembly” to automatically:Create the .fakes file with the minimum XML required to identify the types that will be isolatedSet the build action for the .fakes file to Fakes (a custom MSBuild task)Generate the assembly containing the isolation typesAdd the necessary references including the newly generated assembly
  5. Stubs expose members as fieldsShims expose members as write-only properties
  6. Generic methods are a bit different – they’re overloaded methods rather than fields
  7. AttachBackingFieldTo… auto-wires backing field behavior only when neither the get and set delegates have been assigned
  8. NOTE: Be sure to make your event virtual to get this functionality
  9. Enabled by setting the CallBase propertyOnly works with concrete types – nothing to call on interfacesCallBase isn’t even generated for interface stubs
  10. Default behavior is DefaultValue (Docs say NotImplemented)Change the default behavior by setting the Current property on StubBehaviors
  11. ShimsContext is requiredAlways instantiate within a using block to ensure disposal Shims are not thread-safe and if not disposed, will live as long as the AppDomain
  12. Shims are used in roughly the same was as StubsConstructor overload to access base type members Create a shim for the child and pass it to a shim for the parentMust assign the static constructor delegate before accessing any shim memberDefault is NotImplemented
  13. StubGeneration and ShimGeneration elementsPrevent a type’s generation entirely by setting the disabled attribute on either elementFiltering follows the familiar Clear, Add, Remove pattern
  14. Preliminary & subject to changeAlready found some inaccuraciesDefault behavior for stubsFiltering example uses incorrect schema
  15. HostTypeAttribute “just works” with MSTestRunnable with the Nunit console runner – good luck with the GUI