SlideShare uma empresa 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante 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
 

Semelhante 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
 

Mais 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
 

Mais 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

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 

Último (20)

Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 

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