SlideShare ist ein Scribd-Unternehmen logo
1 von 116
Unit-Testing
Sergey Podolsky
sergey.podolsky@gmail.com
A “unit” is a method or function
A unit test is a piece of a code (usually a
method) that invokes another piece of code and
checks the correctness…
The Basics
We’ve all written unit tests (sort of)
A unit test should have the following
properties:
1. It should be automated and repeatable.
2. It should be easy to implement.
3. Once it’s written, it should remain for future
use.
4. Anyone should be able to run it.
5. It should run at the push of a button.
6. It should run quickly.
You’ve done integration
testing.
“What was I doing until now?”
you might ask.
integration
test
DEFINITION
• Integration testing means testing two or more
dependent software modules as a group.
Test-driven development
Testing Without Frameworks
Console Test
Running coded tests
…handmade Utilities
A first unit test
NUnit
log and notification project
Rules for naming tests
First Blood Test
Checking for expected exceptions
Setup and teardown
Ignoring tests
Setting test categories
Using stubs to break dependencies
• • Defining stubs
• • Refactoring code to use stubs
• • Overcoming encapsulation problems in code
• • Exploring best practices when using stubs
DEFINITION
• An external dependency is an object
in your system that your code under
test interacts with, and over which
you have no control. (Common
examples are filesystems, threads,
memory, time, and so on.)
DEFINITION
• A stub is a controllable replacement for an
existing dependency (or collaborator) in the
system. By using a stub, you can test your
code without dealing with the dependency
directly.
xUnit Test Patterns
by Gerard Meszaros
Fakes
Mocks Stubs
Identifying a filesystem dependency
in LogAn
The problem - an integration test
Direct Dependency test-inhibiting design
the code has some
dependency on an external
resource, which might break
the test even though the
code’s logic is perfectly valid
astronaut analogy
A space shuttle simulator
• Find the interface or API
• Replace the underlying implementation
Introducing a layer of indirection to
avoid a direct dependency on the
filesystem
Introducing a stub to break the
dependency
Refactoring our design to be more
testable
• DEFINITION Refactoring is the act of changing
the code’s design without breaking existing
functionality.
• DEFINITION Seams are places in your code
where you can plug in different functionality,
such as stub classes.
techniques for breaking dependencies
• Extract an interface to allow replacing
underlying implementation.
• Inject stub implementation into a class under
test.
• Receive an interface at the constructor level.
• Receive an interface as a property get or set.
• Get a stub just before a method call.
Extract an interface to allow
replacing underlying
implementation
Extracting a class that touches the
filesystem, and calling it
Extracting an interface from a known
class
Simple stub code that always
returns true
What’s next ???
Still have this:
Inject stub implementation into a
class under test
• Constructor
• Property
• a parameter to the method injection.
• a factory class
• a local factory method
constructor injection
Injecting our stub using constructor
injection
Problems with constructor injection:
more than one stub
Solution 1:
• parameter object
refactoring
create a special class that
contains all the values
needed to initialize a class
Solution 2:
inversion of control
(IoC) containers
• Spring.NET
• Castle Windsor
• Microsoft Unity
• Autofac
• Ninject
• StructureMap
http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx
Another Problem:
• 50 tests against your
constructor
• another dependency
you had not considered
• ????????
• change the call in 50
other tests !!!!!!!!!!!!
Advantages?
Parameters are non-optional for
user!
Receive an interface as a property
get or set
Injecting a stub by adding property
setters to the class under test
When a dependency of the
class under test is optional
dependency has a default
instance created
Use a factory class
Class under test
Test
Factory
Get more about factories in…
Using #if and #endif
with conditional compilation
• • Defining interaction testing
• • Understanding mock objects
• • Differentiating mocks and stubs
• • Exploring mock object best practices
DEFINITION
Interaction testing is testing how an object
sends input to or receives input from other
objects—how that object interacts with other
objects.
DEFINITION
• A mock object is a fake object in the system
that decides whether the unit test has
passed or failed. It does so by verifying
whether the object under test interacted
as expected with the fake object.
• There’s usually no more than one mock per
test.
Example – tree watering
• ❂ State-based testing
• ❂ Interaction testing
Differences between and
stubs can’t fail tests, and mocks can
MockWebService to record messages
that LogAnalyzer will send
Interface
Mock = Stub + ExtraCode
Stub + mock together
• Mock = Email service
• Stub = Web Service
E-mail to admin when web-service falls
Test
Stub - WebService
Mock - Email Service
RULE:
One mock per test
Other fakes = stubs
Stub chains
Solution technique:
A problem:
Isolation (mock object) frameworks
• • Understanding isolation frameworks
• • Defining fake objects
• • Using Rhino Mocks to create stubs and mocks
• • Surveying advanced use cases for mocks and
stubs
• • Exploring arrange-act-assert and record-and-
replay syntax
• • Avoiding common misuses of isolation
frameworks
DEFINITION
• An isolation framework is a set of
programmable APIs that make creating mock
and stub objects much easier.
• Isolation frameworks save the developer from
the need to write repetitive code to test or
simulate object interactions.
A problem:
Complicated interface
Handwritten
stubs
Dynamically creating a fake object
DEFINITION
A is any stub or mock that’s
created at runtime without needing to use a
handwritten implementation of an interface or
subclass.
• record-and-replay model
• arrange-act-assert model
Handwritten
mock
Dynamic Mock
will fail before verify()
strict mock can fail in two ways:
• expected methods aren’t called on it
• an unexpected method is called on it
• expected methods aren’t called on it
nonstrict mock can fail in one way:
nonstrict mock sample
Returning values from fake objects
Order does
not matter
Order
matters
You can also use LastCall to:
• LastCall.Throw(Exception)
• LastCall.Do( yourOwnDelegate )
Creating a stub in Rhino Mocks
Test doesn’t call an expected method
: auto implementing properties
: stub simulating exception
Combining dynamic stubs and mocks
Test logic:
Without frameworks:
With dynamic mocks & stubs
Parameter constraints for mocks and
stubs
LogAnalyzer sends "[Some GUID] Error message“
an example:
"33DFCC9D-D6C5-45ea-A520-A6018C88E490 Out of memory"
Using a string constraint in a test
Here’s the same test using the Text class:
LastCall.Constraints(Text.Contains("abc"));
The four types of constraints in Rhino Mocks
Testing for event-related activities
• Testing that an event has been subscribed to
• Triggering events from mocks and stubs
Testing that an event was registered properly
Triggering events from mocks and stubs
Another way of getting an EventRaiser
object is by using the recording
Arrange-act-assert syntax for isolation
Moq
Rhino
Mocks
Typemock
Isolator
Record-and-replay versus AAA-style
isolation
the same test using AAA syntax
the same test using Typemock Isolator
AAA syntax
Stubs in AAA-style isolation
Current isolation frameworks for .NET
Advantages of isolation frameworks:
❂ Easier parameter verification
❂ Easier verification of multiple method calls
❂ Easier fakes creation
automated build systems
• CruiseControl.NET (cruisecontrol.sourceforge.net)
• TeamCity (JetBrains.com)
• NAnt (nant.sourceforge.net)
• MSBuild
• (http://msdn.microsoft.com/en-us/library/wea2sca5(VS.80).aspx)
• FinalBuilder (www.FinalBuilder.com)
• Visual Build Pro (www.kinook.com)
• Visual Studio Team Foundation Server
(http://msdn.microsoft.com/en-us/teamsystem/default.aspx)
Separate unit and integration tests
(Safe Green Zone)
OR
Abstract test infrastructure class pattern
two test classes that reuse setup method
Template test class pattern
Similar to
contract
helps to test data-layer
CRUD (create, retrieve, update, and delete )
classes

Weitere ähnliche Inhalte

Was ist angesagt?

Unit testing
Unit testingUnit testing
Unit testing
Slideshare
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
Sayedur Rahman
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
suhasreddy1
 
Manual testing concepts course 1
Manual testing concepts course 1Manual testing concepts course 1
Manual testing concepts course 1
Raghu Kiran
 

Was ist angesagt? (20)

Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing
Unit testingUnit testing
Unit testing
 
UNIT TESTING
UNIT TESTINGUNIT TESTING
UNIT TESTING
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
 
Junit
JunitJunit
Junit
 
UNIT TESTING PPT
UNIT TESTING PPTUNIT TESTING PPT
UNIT TESTING PPT
 
Test Automation Framework Designs
Test Automation Framework DesignsTest Automation Framework Designs
Test Automation Framework Designs
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Unit test
Unit testUnit test
Unit test
 
Automated Testing with Agile
Automated Testing with AgileAutomated Testing with Agile
Automated Testing with Agile
 
Unit testing
Unit testingUnit testing
Unit testing
 
Google test training
Google test trainingGoogle test training
Google test training
 
TDD - Test Driven Development
TDD - Test Driven DevelopmentTDD - Test Driven Development
TDD - Test Driven Development
 
Manual testing concepts course 1
Manual testing concepts course 1Manual testing concepts course 1
Manual testing concepts course 1
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
testng
testngtestng
testng
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 
An Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 

Andere mochten auch

Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 

Andere mochten auch (10)

Rest Essentials
Rest EssentialsRest Essentials
Rest Essentials
 
Win at life with unit testing
Win at life with unit testingWin at life with unit testing
Win at life with unit testing
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Unit testing - the hard parts
Unit testing - the hard partsUnit testing - the hard parts
Unit testing - the hard parts
 
Visteme con 'Clean Architecture' que tengo prisas
Visteme con 'Clean Architecture' que tengo prisasVisteme con 'Clean Architecture' que tengo prisas
Visteme con 'Clean Architecture' que tengo prisas
 
Google Protocol Buffers
Google Protocol BuffersGoogle Protocol Buffers
Google Protocol Buffers
 
Tuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issuesTuning Java GC to resolve performance issues
Tuning Java GC to resolve performance issues
 
Enterprise Integration Patterns
Enterprise Integration PatternsEnterprise Integration Patterns
Enterprise Integration Patterns
 

Ähnlich wie Unit Testing

Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
TO THE NEW | Technology
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 

Ähnlich wie Unit Testing (20)

Unit testing
Unit testingUnit testing
Unit testing
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Unit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - KenyaUnit testing and mocking in Python - PyCon 2018 - Kenya
Unit testing and mocking in Python - PyCon 2018 - Kenya
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Microsoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable CodeMicrosoft Fakes, Unit Testing the (almost) Untestable Code
Microsoft Fakes, Unit Testing the (almost) Untestable Code
 
Unit Tests with Microsoft Fakes
Unit Tests with Microsoft FakesUnit Tests with Microsoft Fakes
Unit Tests with Microsoft Fakes
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
How and what to unit test
How and what to unit testHow and what to unit test
How and what to unit test
 
Unit Testing in Swift
Unit Testing in SwiftUnit Testing in Swift
Unit Testing in Swift
 
Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications Automated testing of ASP .Net Core applications
Automated testing of ASP .Net Core applications
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubsIntegration and Unit Testing in Java using Test Doubles like mocks and stubs
Integration and Unit Testing in Java using Test Doubles like mocks and stubs
 
Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!Summit 16: Stop Writing Legacy Code!
Summit 16: Stop Writing Legacy Code!
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Nguyenvandungb seminar
Nguyenvandungb seminarNguyenvandungb seminar
Nguyenvandungb seminar
 

KĂźrzlich hochgeladen

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Bert Jan Schrijver
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 

KĂźrzlich hochgeladen (20)

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
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
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 

Unit Testing