SlideShare una empresa de Scribd logo
1 de 20
Using FakeItEasy
Dror Helper
Senior consultant
drorh@codevalue.net | http://blog.drorhelper.com | @dhelper
• Open-source .NET dynamic fake framework (http://fakeiteasy.github.io/)
• Constrained (inheritance based)
• Can be freely downloaded from GitHub:
https://github.com/FakeItEasy/FakeItEasy
• Has a NuGet Package
FakeItEasy
• No need to write & maintain fake objects
• Helpful exception messages identify where a test went wrong
• Simple AAA fluent interface
– Single point of entry: “A.”
– Explicit assertions
• Default behavior is usually the desired behavior
• Flexible parameter handling
• Refactoring safe
Benefits
Use NuGet to get latest version
• Interfaces
• Classes
– Not sealed
– Not static
– Have at least one public/protected c’tor that FakeItEasy can
create or obtain
What types can be faked
Since FakeItEasy fake by creating a derived class only the following
methods/properties can be faked:
• Virtual
• Abstract
• Defined on an interface
The following can not be faked:
• Static
• Extension
• Non-virtual or Sealed
What members can be overridden
var fakeDependency = A.Fake<IDependency>();
Creating fake objects
Remember: c’tor will be called when creating a fake
Solution: Assign specific arguments to the c’tor – in a strongly typed way
A.Fake<DependencyClass>(x => x.WithArgumentsForConstructor(() => new DependencyClass(p1)));
A.Fake<DependencyClass>(x => x.OnFakeCreated((c => c.Method1())));
Define a method to run after object created
A.Fake<DependencyClass>(x => x.Implements(typeof(IOther)));
Specify additional interfaces to be implemented. Useful when fake skips memebers because they have
been explicitly implemented on the faked class
And more - https://github.com/FakeItEasy/FakeItEasy/wiki/Creating-Fakes
• Caution: Non-overideable methods call original
implementation
• Methods automatically return:
– string  string.Empty
– Non-fakeable types (incl. value-types)  default(T)
– Fakeable T  Fake of T
• Unless told otherwise (usually not a good idea)
Default behavior
var fake = A.Fake<IDatabase>(builder => builder.Strict());
Use A.CallTo to define behavior on method/property or object
Setting behavior on fake objects
Specify behavior to all methods and properties (return null if not void)
A.CallTo(fakeDependency).DoesNothing();
Specify return value for single method
A.CallTo(() => fakeDependency.SomeMethod()).Returns(42);
A.CallTo(() => fakeDependency.SomeMethod()).DoesNothing();
Throw exception
A.CallTo(() => fakeDependency.SomeMethod()).Throws<ApplicationException>();
A.CallTo(() => fakeDependency.SomeMethod()).Throws(new ApplicationException("Boom!"));
Invoke custom code
A.CallTo(() => fakeDependency.SomeMethod()).Invokes(() => otherClass.Method());
Although can set properties using A.CallTo there’s an easier and simpler way.
Setting a value on any fakeable property would cause its getter to return
the same value
Read Write property behavior (auto property)
var fakeDependency = A.Fake<IDependency>();
fakeDependency.SomeProperty = 5;
Console.Out.WriteLine(fakeDependency.SomeProperty); // print 5
• Uses exactly the same syntax as setting behavior
• Following by MustHaveHappened/MustNotHaveHappened
Asserting methods were called
// Asserting that a call has happened at least once.
// The following two lines are equivalent.
A.CallTo(() => foo.Bar()).MustHaveHappened(Repeated.AtLeast.Once); // or
A.CallTo(() => foo.Bar()).MustHaveHappened();
// To contrast, assert that a call has happened exactly once.
A.CallTo(() => foo.Bar()).MustHaveHappened(Repeated.Exactly.Once);
// Asserting that a call has not happened.
// The following two lines are equivalent.
A.CallTo(() => foo.Bar()).MustNotHaveHappened(); // or
A.CallTo(() => foo.Bar()).MustHaveHappened(Repeated.Never);
Caution: test results and not method calls to avoid fragile tests
When using actual values these values would be checked before setting
behavior or verifying calls.
Specific arguments constraints when for behavior are over-specification and
should be avoided (usually):
A.CallTo(() => foo.Bar("hello", 17)).Returns(true);
Specific arguments constraints for verify means that we want to make sure that
the method was called/not called with these specific arguments:
A.CallTo(() => foo.Bar("hello", 17)).MustHaveHappened();
Argument Constraints – match exactly
Recommended when setting behavior:
A.CallTo(() => foo.Bar(A<string>.Ignored, A<int>.Ignored)).Returns(true);
Can use ‘_’ as a shorthand
A.CallTo(() => foo.Bar(A<string>._, A<int>._)).Returns(true);
For complicated constraints use “that” method:
A.CallTo(
() => foo.Bar(A<string>.That.IsEmpty(), A<int>.That.IsGreaterThan(0))).Returns(true);
Or use custom constraints –
https://github.com/FakeItEasy/FakeItEasy/wiki/Argument-Constraints
Argument Constraints – match Any arguments
Raise event from fake object
Used in tests of functionality that is triggered by an event
Raising events
// Raise the event!
fake.OnEvent += Raise.With(EventArgs.Empty).Now;
// Use the overload for empty event args
fake.OnEvent += Raise.WithEmpty().Now;
// Specify sender explicitly:
fake.OnEvent += Raise.With(sender: robot, e: EventArgs.Empty).Now;
Can create a value that changes over time
Setting behavior that change over time
// Return according to sequalnce until finished
// Afterwards will not take an item from the sequence,
// but will rely on other configured (or default) behaviour
A.CallTo(() => fake.Count).ReturnsNextFromSequence(1,2,3,5,8,12,20);
// Returns the number of times the method has been called
int counter = 0;
A.CallTo(() => fake.Count).ReturnsLazily(() => ++counter);
// set up an action that can run forever, unless superseded
A.CallTo(() => fake.Bar()).Returns(true);
// set up a one-time exception which will be used for the first call
A.CallTo(() => fake.Bar()).Throws<Exception>().Once();
Setting behavior on same method several times creates a call sequence
Caution: Use sparsely, usually an over-specification  fragile tests
Should not be used frequently – remember the “single assert per test rule” -
only use when the order is the assertion.
• Example: read from DB before data was updated.
Ordered assertions
using (var scope = Fake.CreateScope())
}
// Act
worker.JustDoIt();
// Assert
using (scope.OrderedAssertions())
}
A.CallTo(() => unitOfWorkFactory.BeginWork()).MustHaveHappened();
A.CallTo(() => usefulCollaborator.JustDoIt()).MustHaveHappened();
A.CallTo(() => unitOfWork.Dispose()).MustHaveHappened();
}
{
Add the following to the AssembltInfo.cs file in the Assembly under test:
• [assembly: InternalsVisibleTo(“test assembly name”)] for the type to be
visible to the test assembly
• [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2,
PublicKey=00240000048000009400000006020000002400005253413100
04000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc98916
05d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0
bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46
ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be1
1e6a7d3113e92484cf7045cc7“)]
Faking internal objects
Dependency injection
How can we pass the fake object to the production code?
• Factory method/class
• Constructor/property Injection
• Object locator pattern
Things to remember when using FakeItEasy
1. Code to interfaces (LSP)
2. Declare methods as virtual
3. Use dependency injection
Dror Helper
C: 972.05.7668543
e: drorh@codevalue.net
B: blog.drorhelper.com
w: www.codevalue.net

Más contenido relacionado

La actualidad más candente

A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalQA or the Highway
 
[Mac] automation testing technical sharing - 2013 dec
[Mac] automation testing  technical sharing - 2013 dec[Mac] automation testing  technical sharing - 2013 dec
[Mac] automation testing technical sharing - 2013 decChloe Chen
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?Knoldus Inc.
 
Introductionandgreetings
IntroductionandgreetingsIntroductionandgreetings
IntroductionandgreetingsPozz ZaRat
 
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and NimbleTDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and NimbleJianbin LIN
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with MockitoAlexander De Leon
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in SwiftVincent Pradeilles
 
Writing simple buffer_overflow_exploits
Writing simple buffer_overflow_exploitsWriting simple buffer_overflow_exploits
Writing simple buffer_overflow_exploitsD4rk357 a
 
Getting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseGetting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseTom Arend
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 

La actualidad más candente (19)

Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
Friendly Functional Programming
Friendly Functional ProgrammingFriendly Functional Programming
Friendly Functional Programming
 
A Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert FornalA Lifecycle Of Code Under Test by Robert Fornal
A Lifecycle Of Code Under Test by Robert Fornal
 
[Mac] automation testing technical sharing - 2013 dec
[Mac] automation testing  technical sharing - 2013 dec[Mac] automation testing  technical sharing - 2013 dec
[Mac] automation testing technical sharing - 2013 dec
 
Backday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkitBackday Xebia : Akka, the reactive toolkit
Backday Xebia : Akka, the reactive toolkit
 
Fiber supervision in ZIO
Fiber supervision in ZIOFiber supervision in ZIO
Fiber supervision in ZIO
 
How To Use IO Monads in Scala?
 How To Use IO Monads in Scala? How To Use IO Monads in Scala?
How To Use IO Monads in Scala?
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Introductionandgreetings
IntroductionandgreetingsIntroductionandgreetings
Introductionandgreetings
 
Berlin meetup
Berlin meetupBerlin meetup
Berlin meetup
 
ZIO Queue
ZIO QueueZIO Queue
ZIO Queue
 
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and NimbleTDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
TDD - Test Driven Development in Swift (iOS) with Cuckoo, Quick and Nimble
 
Basic Unit Testing with Mockito
Basic Unit Testing with MockitoBasic Unit Testing with Mockito
Basic Unit Testing with Mockito
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
Writing simple buffer_overflow_exploits
Writing simple buffer_overflow_exploitsWriting simple buffer_overflow_exploits
Writing simple buffer_overflow_exploits
 
Getting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in EclipseGetting Started with Maven and Cucumber in Eclipse
Getting Started with Maven and Cucumber in Eclipse
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 

Similar a Using FakeIteasy

SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutDror Helper
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstituteSuresh Loganatha
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My HeartBui Kiet
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock TutorialSbin m
 

Similar a Using FakeIteasy (20)

Easy mock
Easy mockEasy mock
Easy mock
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Exception
ExceptionException
Exception
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Introduction to nsubstitute
Introduction to nsubstituteIntroduction to nsubstitute
Introduction to nsubstitute
 
Day 5
Day 5Day 5
Day 5
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 
Easymock Tutorial
Easymock TutorialEasymock Tutorial
Easymock Tutorial
 

Más de Dror Helper

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutDror Helper
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Dror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better codeDror Helper
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better codeDror Helper
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with awsDror Helper
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutDror Helper
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agileDror Helper
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreDror Helper
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET coreDror Helper
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot netDror Helper
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyDror Helper
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy codeDror Helper
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowDror Helper
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing toolsDror Helper
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developersDror Helper
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupDror Helper
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctlyDror Helper
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbgDror Helper
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent codeDror Helper
 

Más de Dror Helper (20)

Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'Debugging with visual studio beyond 'F5'
Debugging with visual studio beyond 'F5'
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
From clever code to better code
From clever code to better codeFrom clever code to better code
From clever code to better code
 
A software developer guide to working with aws
A software developer guide to working with awsA software developer guide to working with aws
A software developer guide to working with aws
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
The role of the architect in agile
The role of the architect in agileThe role of the architect in agile
The role of the architect in agile
 
Harnessing the power of aws using dot net core
Harnessing the power of aws using dot net coreHarnessing the power of aws using dot net core
Harnessing the power of aws using dot net core
 
Developing multi-platform microservices using .NET core
 Developing multi-platform microservices using .NET core Developing multi-platform microservices using .NET core
Developing multi-platform microservices using .NET core
 
Harnessing the power of aws using dot net
Harnessing the power of aws using dot netHarnessing the power of aws using dot net
Harnessing the power of aws using dot net
 
C++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the uglyC++ Unit testing - the good, the bad & the ugly
C++ Unit testing - the good, the bad & the ugly
 
Working with c++ legacy code
Working with c++ legacy codeWorking with c++ legacy code
Working with c++ legacy code
 
Visual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should knowVisual Studio tricks every dot net developer should know
Visual Studio tricks every dot net developer should know
 
Secret unit testing tools
Secret unit testing toolsSecret unit testing tools
Secret unit testing tools
 
Electronics 101 for software developers
Electronics 101 for software developersElectronics 101 for software developers
Electronics 101 for software developers
 
Navigating the xDD Alphabet Soup
Navigating the xDD Alphabet SoupNavigating the xDD Alphabet Soup
Navigating the xDD Alphabet Soup
 
Building unit tests correctly
Building unit tests correctlyBuilding unit tests correctly
Building unit tests correctly
 
Who’s afraid of WinDbg
Who’s afraid of WinDbgWho’s afraid of WinDbg
Who’s afraid of WinDbg
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 

Último

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 

Último (20)

Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 

Using FakeIteasy

  • 1. Using FakeItEasy Dror Helper Senior consultant drorh@codevalue.net | http://blog.drorhelper.com | @dhelper
  • 2. • Open-source .NET dynamic fake framework (http://fakeiteasy.github.io/) • Constrained (inheritance based) • Can be freely downloaded from GitHub: https://github.com/FakeItEasy/FakeItEasy • Has a NuGet Package FakeItEasy
  • 3. • No need to write & maintain fake objects • Helpful exception messages identify where a test went wrong • Simple AAA fluent interface – Single point of entry: “A.” – Explicit assertions • Default behavior is usually the desired behavior • Flexible parameter handling • Refactoring safe Benefits
  • 4. Use NuGet to get latest version
  • 5. • Interfaces • Classes – Not sealed – Not static – Have at least one public/protected c’tor that FakeItEasy can create or obtain What types can be faked
  • 6. Since FakeItEasy fake by creating a derived class only the following methods/properties can be faked: • Virtual • Abstract • Defined on an interface The following can not be faked: • Static • Extension • Non-virtual or Sealed What members can be overridden
  • 7. var fakeDependency = A.Fake<IDependency>(); Creating fake objects Remember: c’tor will be called when creating a fake Solution: Assign specific arguments to the c’tor – in a strongly typed way A.Fake<DependencyClass>(x => x.WithArgumentsForConstructor(() => new DependencyClass(p1))); A.Fake<DependencyClass>(x => x.OnFakeCreated((c => c.Method1()))); Define a method to run after object created A.Fake<DependencyClass>(x => x.Implements(typeof(IOther))); Specify additional interfaces to be implemented. Useful when fake skips memebers because they have been explicitly implemented on the faked class And more - https://github.com/FakeItEasy/FakeItEasy/wiki/Creating-Fakes
  • 8. • Caution: Non-overideable methods call original implementation • Methods automatically return: – string  string.Empty – Non-fakeable types (incl. value-types)  default(T) – Fakeable T  Fake of T • Unless told otherwise (usually not a good idea) Default behavior var fake = A.Fake<IDatabase>(builder => builder.Strict());
  • 9. Use A.CallTo to define behavior on method/property or object Setting behavior on fake objects Specify behavior to all methods and properties (return null if not void) A.CallTo(fakeDependency).DoesNothing(); Specify return value for single method A.CallTo(() => fakeDependency.SomeMethod()).Returns(42); A.CallTo(() => fakeDependency.SomeMethod()).DoesNothing(); Throw exception A.CallTo(() => fakeDependency.SomeMethod()).Throws<ApplicationException>(); A.CallTo(() => fakeDependency.SomeMethod()).Throws(new ApplicationException("Boom!")); Invoke custom code A.CallTo(() => fakeDependency.SomeMethod()).Invokes(() => otherClass.Method());
  • 10. Although can set properties using A.CallTo there’s an easier and simpler way. Setting a value on any fakeable property would cause its getter to return the same value Read Write property behavior (auto property) var fakeDependency = A.Fake<IDependency>(); fakeDependency.SomeProperty = 5; Console.Out.WriteLine(fakeDependency.SomeProperty); // print 5
  • 11. • Uses exactly the same syntax as setting behavior • Following by MustHaveHappened/MustNotHaveHappened Asserting methods were called // Asserting that a call has happened at least once. // The following two lines are equivalent. A.CallTo(() => foo.Bar()).MustHaveHappened(Repeated.AtLeast.Once); // or A.CallTo(() => foo.Bar()).MustHaveHappened(); // To contrast, assert that a call has happened exactly once. A.CallTo(() => foo.Bar()).MustHaveHappened(Repeated.Exactly.Once); // Asserting that a call has not happened. // The following two lines are equivalent. A.CallTo(() => foo.Bar()).MustNotHaveHappened(); // or A.CallTo(() => foo.Bar()).MustHaveHappened(Repeated.Never); Caution: test results and not method calls to avoid fragile tests
  • 12. When using actual values these values would be checked before setting behavior or verifying calls. Specific arguments constraints when for behavior are over-specification and should be avoided (usually): A.CallTo(() => foo.Bar("hello", 17)).Returns(true); Specific arguments constraints for verify means that we want to make sure that the method was called/not called with these specific arguments: A.CallTo(() => foo.Bar("hello", 17)).MustHaveHappened(); Argument Constraints – match exactly
  • 13. Recommended when setting behavior: A.CallTo(() => foo.Bar(A<string>.Ignored, A<int>.Ignored)).Returns(true); Can use ‘_’ as a shorthand A.CallTo(() => foo.Bar(A<string>._, A<int>._)).Returns(true); For complicated constraints use “that” method: A.CallTo( () => foo.Bar(A<string>.That.IsEmpty(), A<int>.That.IsGreaterThan(0))).Returns(true); Or use custom constraints – https://github.com/FakeItEasy/FakeItEasy/wiki/Argument-Constraints Argument Constraints – match Any arguments
  • 14. Raise event from fake object Used in tests of functionality that is triggered by an event Raising events // Raise the event! fake.OnEvent += Raise.With(EventArgs.Empty).Now; // Use the overload for empty event args fake.OnEvent += Raise.WithEmpty().Now; // Specify sender explicitly: fake.OnEvent += Raise.With(sender: robot, e: EventArgs.Empty).Now;
  • 15. Can create a value that changes over time Setting behavior that change over time // Return according to sequalnce until finished // Afterwards will not take an item from the sequence, // but will rely on other configured (or default) behaviour A.CallTo(() => fake.Count).ReturnsNextFromSequence(1,2,3,5,8,12,20); // Returns the number of times the method has been called int counter = 0; A.CallTo(() => fake.Count).ReturnsLazily(() => ++counter); // set up an action that can run forever, unless superseded A.CallTo(() => fake.Bar()).Returns(true); // set up a one-time exception which will be used for the first call A.CallTo(() => fake.Bar()).Throws<Exception>().Once(); Setting behavior on same method several times creates a call sequence Caution: Use sparsely, usually an over-specification  fragile tests
  • 16. Should not be used frequently – remember the “single assert per test rule” - only use when the order is the assertion. • Example: read from DB before data was updated. Ordered assertions using (var scope = Fake.CreateScope()) } // Act worker.JustDoIt(); // Assert using (scope.OrderedAssertions()) } A.CallTo(() => unitOfWorkFactory.BeginWork()).MustHaveHappened(); A.CallTo(() => usefulCollaborator.JustDoIt()).MustHaveHappened(); A.CallTo(() => unitOfWork.Dispose()).MustHaveHappened(); } {
  • 17. Add the following to the AssembltInfo.cs file in the Assembly under test: • [assembly: InternalsVisibleTo(“test assembly name”)] for the type to be visible to the test assembly • [assembly: InternalsVisibleTo("DynamicProxyGenAssembly2, PublicKey=00240000048000009400000006020000002400005253413100 04000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc98916 05d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0 bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46 ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be1 1e6a7d3113e92484cf7045cc7“)] Faking internal objects
  • 18. Dependency injection How can we pass the fake object to the production code? • Factory method/class • Constructor/property Injection • Object locator pattern
  • 19. Things to remember when using FakeItEasy 1. Code to interfaces (LSP) 2. Declare methods as virtual 3. Use dependency injection
  • 20. Dror Helper C: 972.05.7668543 e: drorh@codevalue.net B: blog.drorhelper.com w: www.codevalue.net