SlideShare a Scribd company logo
1 of 24
Unit Testing
By Vinod (Architect) – Crestron Electronics
What is a UNIT OF WORK?
• A unit of work is the sum of actions that take place between the invocation of a
public method in the system and a single noticeable end result by a test of
that system. A noticeable end result can be observed without looking at the
internal state of the system and only through its public APIs and behavior
What is a unit test?
• A unit test is an automated piece of code that invokes the unit of work being
tested, and then checks some assumptions about a single end result of that
unit. A unit test is almost always written using a unit testing framework. It can be
written easily and runs quickly. It’s trustworthy, readable, and maintainable.
It’s consistent in its results as long as production code hasn’t changed.
PROPERTIES OF A GOOD UNIT TEST
• It should be automated and repeatable.
• It should be easy to implement.
• It should be relevant tomorrow.
• Anyone should be able to run it at the push of a button.
• It should run quickly.
• It should be consistent in its results (it always returns the same result if you don’t
change anything between runs).
• It should have full control of the unit under test.
• It should be fully isolated (runs independently of other tests).
• When it fails, it should be easy to detect what was expected and determine how to
pinpoint the problem.
INTEGRATION TESTS
• Integration testing is testing a unit of work without having full control over all of
it and using one or more of its real dependencies, such as time, network,
database, threads, random number generators, and so on
• Difference between Unit Test & Integration Test
• An integration test uses real dependencies; unit tests isolate the unit of work from its
dependencies so that they’re easily consistent in their results and can easily control and
simulate any aspect of the unit’s behaviour.
Test-driven development (TDD)
Traditional way of unit testing TDD
Techniques of TDD
• Write a failing test to prove code or functionality is missing from the end product
• The test will fail to compile
• After adding production code, the test will compile
• The test will now run, and fail because no logic is written yet
• Make the test pass by writing production code that meets the expectations of your
test
• Refactor your code
Benefits of TDD
• One of the biggest benefits of TDD nobody tells you about is that by seeing a test
fail, and then seeing it pass without changing the test, you’re basically testing
the test itself
Basic rules for placing and naming tests
NUnit attributes
[TestFixture]
public class LogAnalyzerTests
{
[Test]
public void
IsValidFileName_BadExtension_ReturnsFalse()
{
LogAnalyzer analyzer = new LogAnalyzer();
bool result =
analyzer.IsValidLogFileName("filewithbadextension
.foo");
Assert.False(result);
}
}
A unit test usually
comprises three main
actions
1. Arrange objects,
creating and setting
them up as necessary
2. Act on an object
3. Assert that something is
as expected
The Assert class
• Assert.True (some Boolean expression)
• Assert.False (some Boolean expression)
• Assert.AreEqual(2, 1+1, "Math is broken");
• Assert.AreSame(int.Parse("1"),int.Parse("1"),"this test should fail")
TDD - Red-Green-
Refactor
1. start with a failing test
2. pass it
3. make your code
readable and
more maintainable
Parameterized Tests
Parameterized Tests
Setup and teardown
NUnit
performs setup and
teardown actions before
and after (respectively)
every test method.
Setup and teardown
[TestFixtureSetUp] and
[TestFixtureTearDown] allow setting up
state
once before all the tests in a specific class
run and once after all the tests have been
run (once per test fixture)
You almost never, ever use TearDown or
TestFixture methods in unit test projects
If you do, you’re very likely writing an
integration test, where you’re touching the
filesystem or a database, and you need to clean
up the disk or the DB after the tests.
Use it only to “reset” the state of a static variable
or singleton in memory
between tests
Checking for expected exceptions
public class LogAnalyzer
{
public bool IsValidLogFileName(string
fileName)
{
…
if (string.IsNullOrEmpty(fileName))
{
throw new ArgumentException(
"filename has to be provided");
}
…
}
}
[Test]
[ExpectedException(typeof(ArgumentException),
ExpectedMessage ="filename has to be
provided")]
public void
IsValidFileName_EmptyFileName_ThrowsException
()
{
m_analyzer.IsValidLogFileName(string.Empty);
}
private LogAnalyzer MakeAnalyzer()
{
return new LogAnalyzer();
}
Factory Method
Checking for expected exceptions – Better way
Ignoring tests
[Test]
[Ignore("there is a problem with this
test")]
public void
IsValidFileName_ValidFile_ReturnsTrue()
{
/// ...
}
State-based testing
State-based testing (also called state
verification) determines whether
the exercised method worked correctly
by examining the changed behavior
of the system under test and its
collaborators (dependencies) after the
method
is exercised.
Stubs
• External Dependency
• 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.)
• Stub
• 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
Stub
• Your method has a direct
dependency on the filesystem. The
design of the object model under test
inhibits you from testing it as a unit
test; it promotes integration testing.
Stub
• Seams
Seams are places in your code where you
can plug in different functionality, such
as
stub classes,
adding a constructor parameter,
adding a public settable property,
making a method virtual so it can be
overridden,
Or externalizing a delegate as a
parameter or property so that it can be
set from outside a class.
Eg: IExtensionManager is a Seam
Fake objects
• Seams
Seams are places in your code where you
can plug in different functionality, such
as
stub classes,
adding a constructor parameter,
adding a public settable property,
making a method virtual so it can be
overridden,
Or externalizing a delegate as a
parameter or property so that it can be
set from outside a class.
Eg: IExtensionManager is a Seam
Thank You

More Related Content

What's hot

Writing good unit test
Writing good unit testWriting good unit test
Writing good unit testLucy Lu
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration TestingDavid Berliner
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnitkleinron
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseUTC Fire & Security
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveAlvaro Videla
 
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 nispas
 
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 NUnitweili_at_slideshare
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDDDror Helper
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldDror Helper
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)Foyzul Karim
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Thomas Weller
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Unit testing
Unit testingUnit testing
Unit testingjeslie
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test PatternsFrank Appel
 

What's hot (20)

Nunit
NunitNunit
Nunit
 
Writing good unit test
Writing good unit testWriting good unit test
Writing good unit test
 
Unit and integration Testing
Unit and integration TestingUnit and integration Testing
Unit and integration Testing
 
Unit testing with NUnit
Unit testing with NUnitUnit testing with NUnit
Unit testing with NUnit
 
Test driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + EclipseTest driven development in .Net - 2010 + Eclipse
Test driven development in .Net - 2010 + Eclipse
 
Unit Test + Functional Programming = Love
Unit Test + Functional Programming = LoveUnit Test + Functional Programming = Love
Unit Test + Functional Programming = Love
 
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 Test Using NUnit
An Introduction to Unit Test Using NUnitAn Introduction to Unit Test Using NUnit
An Introduction to Unit Test Using NUnit
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit tests & TDD
Unit tests & TDDUnit tests & TDD
Unit tests & TDD
 
Benefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real WorldBenefit From Unit Testing In The Real World
Benefit From Unit Testing In The Real World
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
Introduction to testing with MSTest, Visual Studio, and Team Foundation Serve...
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
N Unit Presentation
N Unit PresentationN Unit Presentation
N Unit Presentation
 
Unit testing
Unit testingUnit testing
Unit testing
 
Tdd & unit test
Tdd & unit testTdd & unit test
Tdd & unit test
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 

Similar to Unit testing

An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingSahar Nofal
 
Unit & integration testing
Unit & integration testingUnit & integration testing
Unit & integration testingPavlo Hodysh
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayJordi Pradel
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentMeilan Ou
 
Software engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit designSoftware engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit designMaitree Patel
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptxmianshafa
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Software Testing Strategies
Software Testing StrategiesSoftware Testing Strategies
Software Testing StrategiesAlpana Bhaskar
 
Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overviewAlex Pop
 
Good Unit Tests Ask For Quality Code
Good Unit Tests Ask For Quality CodeGood Unit Tests Ask For Quality Code
Good Unit Tests Ask For Quality CodeFlorin Coros
 
Module V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdfModule V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdfadhithanr
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolatorMaslowB
 
testing strategies and tactics
 testing strategies and tactics testing strategies and tactics
testing strategies and tacticsPreeti Mishra
 

Similar to Unit testing (20)

An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
Unit & integration testing
Unit & integration testingUnit & integration testing
Unit & integration testing
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Lecture 21
Lecture 21Lecture 21
Lecture 21
 
Agile Software Testing the Agilogy Way
Agile Software Testing the Agilogy WayAgile Software Testing the Agilogy Way
Agile Software Testing the Agilogy Way
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Testing Angular
Testing AngularTesting Angular
Testing Angular
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
Software engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit designSoftware engineering Testing technique,test case,test suit design
Software engineering Testing technique,test case,test suit design
 
Week 14 Unit Testing.pptx
Week 14  Unit Testing.pptxWeek 14  Unit Testing.pptx
Week 14 Unit Testing.pptx
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Software Testing Strategies
Software Testing StrategiesSoftware Testing Strategies
Software Testing Strategies
 
Automated testing overview
Automated testing overviewAutomated testing overview
Automated testing overview
 
Good Unit Tests Ask For Quality Code
Good Unit Tests Ask For Quality CodeGood Unit Tests Ask For Quality Code
Good Unit Tests Ask For Quality Code
 
Module V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdfModule V - Software Testing Strategies.pdf
Module V - Software Testing Strategies.pdf
 
Type mock isolator
Type mock isolatorType mock isolator
Type mock isolator
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
testing strategies and tactics
 testing strategies and tactics testing strategies and tactics
testing strategies and tactics
 

More from Vinod Wilson

Representational state transfer (rest) architectural style1.1
Representational state transfer (rest) architectural style1.1Representational state transfer (rest) architectural style1.1
Representational state transfer (rest) architectural style1.1Vinod Wilson
 
UI Design - Organizing the page
UI Design - Organizing the pageUI Design - Organizing the page
UI Design - Organizing the pageVinod Wilson
 
Service oriented architecture introduction
Service oriented architecture   introductionService oriented architecture   introduction
Service oriented architecture introductionVinod Wilson
 
Togaf – models for phase A
Togaf – models for phase ATogaf – models for phase A
Togaf – models for phase AVinod Wilson
 
The components of togaf architecture
The components of togaf architectureThe components of togaf architecture
The components of togaf architectureVinod Wilson
 
Togaf – architecture development method (adm)
Togaf – architecture development method (adm)Togaf – architecture development method (adm)
Togaf – architecture development method (adm)Vinod Wilson
 
Togaf 9 introduction
Togaf 9 introductionTogaf 9 introduction
Togaf 9 introductionVinod Wilson
 
D3 data visualization
D3 data visualizationD3 data visualization
D3 data visualizationVinod Wilson
 
Event driven architecture
Event driven architectureEvent driven architecture
Event driven architectureVinod Wilson
 
Domain driven design simplified
Domain driven design simplifiedDomain driven design simplified
Domain driven design simplifiedVinod Wilson
 
Developing saas application in azure
Developing saas application in azureDeveloping saas application in azure
Developing saas application in azureVinod Wilson
 
Iot cloud service v2.0
Iot cloud service v2.0Iot cloud service v2.0
Iot cloud service v2.0Vinod Wilson
 
IoT mobile app device cloud identity and security architecture
IoT mobile app device cloud identity and security architectureIoT mobile app device cloud identity and security architecture
IoT mobile app device cloud identity and security architectureVinod Wilson
 

More from Vinod Wilson (15)

Representational state transfer (rest) architectural style1.1
Representational state transfer (rest) architectural style1.1Representational state transfer (rest) architectural style1.1
Representational state transfer (rest) architectural style1.1
 
UI Design - Organizing the page
UI Design - Organizing the pageUI Design - Organizing the page
UI Design - Organizing the page
 
Service oriented architecture introduction
Service oriented architecture   introductionService oriented architecture   introduction
Service oriented architecture introduction
 
Togaf – models for phase A
Togaf – models for phase ATogaf – models for phase A
Togaf – models for phase A
 
The components of togaf architecture
The components of togaf architectureThe components of togaf architecture
The components of togaf architecture
 
Togaf – architecture development method (adm)
Togaf – architecture development method (adm)Togaf – architecture development method (adm)
Togaf – architecture development method (adm)
 
Togaf 9 introduction
Togaf 9 introductionTogaf 9 introduction
Togaf 9 introduction
 
Ssas mdx language
Ssas mdx languageSsas mdx language
Ssas mdx language
 
D3 data visualization
D3 data visualizationD3 data visualization
D3 data visualization
 
Event driven architecture
Event driven architectureEvent driven architecture
Event driven architecture
 
Domain driven design simplified
Domain driven design simplifiedDomain driven design simplified
Domain driven design simplified
 
Data partitioning
Data partitioningData partitioning
Data partitioning
 
Developing saas application in azure
Developing saas application in azureDeveloping saas application in azure
Developing saas application in azure
 
Iot cloud service v2.0
Iot cloud service v2.0Iot cloud service v2.0
Iot cloud service v2.0
 
IoT mobile app device cloud identity and security architecture
IoT mobile app device cloud identity and security architectureIoT mobile app device cloud identity and security architecture
IoT mobile app device cloud identity and security architecture
 

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 

Unit testing

  • 1. Unit Testing By Vinod (Architect) – Crestron Electronics
  • 2. What is a UNIT OF WORK? • A unit of work is the sum of actions that take place between the invocation of a public method in the system and a single noticeable end result by a test of that system. A noticeable end result can be observed without looking at the internal state of the system and only through its public APIs and behavior
  • 3. What is a unit test? • A unit test is an automated piece of code that invokes the unit of work being tested, and then checks some assumptions about a single end result of that unit. A unit test is almost always written using a unit testing framework. It can be written easily and runs quickly. It’s trustworthy, readable, and maintainable. It’s consistent in its results as long as production code hasn’t changed.
  • 4. PROPERTIES OF A GOOD UNIT TEST • It should be automated and repeatable. • It should be easy to implement. • It should be relevant tomorrow. • Anyone should be able to run it at the push of a button. • It should run quickly. • It should be consistent in its results (it always returns the same result if you don’t change anything between runs). • It should have full control of the unit under test. • It should be fully isolated (runs independently of other tests). • When it fails, it should be easy to detect what was expected and determine how to pinpoint the problem.
  • 5. INTEGRATION TESTS • Integration testing is testing a unit of work without having full control over all of it and using one or more of its real dependencies, such as time, network, database, threads, random number generators, and so on • Difference between Unit Test & Integration Test • An integration test uses real dependencies; unit tests isolate the unit of work from its dependencies so that they’re easily consistent in their results and can easily control and simulate any aspect of the unit’s behaviour.
  • 7. Techniques of TDD • Write a failing test to prove code or functionality is missing from the end product • The test will fail to compile • After adding production code, the test will compile • The test will now run, and fail because no logic is written yet • Make the test pass by writing production code that meets the expectations of your test • Refactor your code
  • 8. Benefits of TDD • One of the biggest benefits of TDD nobody tells you about is that by seeing a test fail, and then seeing it pass without changing the test, you’re basically testing the test itself
  • 9. Basic rules for placing and naming tests
  • 10. NUnit attributes [TestFixture] public class LogAnalyzerTests { [Test] public void IsValidFileName_BadExtension_ReturnsFalse() { LogAnalyzer analyzer = new LogAnalyzer(); bool result = analyzer.IsValidLogFileName("filewithbadextension .foo"); Assert.False(result); } } A unit test usually comprises three main actions 1. Arrange objects, creating and setting them up as necessary 2. Act on an object 3. Assert that something is as expected
  • 11. The Assert class • Assert.True (some Boolean expression) • Assert.False (some Boolean expression) • Assert.AreEqual(2, 1+1, "Math is broken"); • Assert.AreSame(int.Parse("1"),int.Parse("1"),"this test should fail") TDD - Red-Green- Refactor 1. start with a failing test 2. pass it 3. make your code readable and more maintainable
  • 14. Setup and teardown NUnit performs setup and teardown actions before and after (respectively) every test method.
  • 15. Setup and teardown [TestFixtureSetUp] and [TestFixtureTearDown] allow setting up state once before all the tests in a specific class run and once after all the tests have been run (once per test fixture) You almost never, ever use TearDown or TestFixture methods in unit test projects If you do, you’re very likely writing an integration test, where you’re touching the filesystem or a database, and you need to clean up the disk or the DB after the tests. Use it only to “reset” the state of a static variable or singleton in memory between tests
  • 16. Checking for expected exceptions public class LogAnalyzer { public bool IsValidLogFileName(string fileName) { … if (string.IsNullOrEmpty(fileName)) { throw new ArgumentException( "filename has to be provided"); } … } } [Test] [ExpectedException(typeof(ArgumentException), ExpectedMessage ="filename has to be provided")] public void IsValidFileName_EmptyFileName_ThrowsException () { m_analyzer.IsValidLogFileName(string.Empty); } private LogAnalyzer MakeAnalyzer() { return new LogAnalyzer(); } Factory Method
  • 17. Checking for expected exceptions – Better way
  • 18. Ignoring tests [Test] [Ignore("there is a problem with this test")] public void IsValidFileName_ValidFile_ReturnsTrue() { /// ... }
  • 19. State-based testing State-based testing (also called state verification) determines whether the exercised method worked correctly by examining the changed behavior of the system under test and its collaborators (dependencies) after the method is exercised.
  • 20. Stubs • External Dependency • 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.) • Stub • 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
  • 21. Stub • Your method has a direct dependency on the filesystem. The design of the object model under test inhibits you from testing it as a unit test; it promotes integration testing.
  • 22. Stub • Seams Seams are places in your code where you can plug in different functionality, such as stub classes, adding a constructor parameter, adding a public settable property, making a method virtual so it can be overridden, Or externalizing a delegate as a parameter or property so that it can be set from outside a class. Eg: IExtensionManager is a Seam
  • 23. Fake objects • Seams Seams are places in your code where you can plug in different functionality, such as stub classes, adding a constructor parameter, adding a public settable property, making a method virtual so it can be overridden, Or externalizing a delegate as a parameter or property so that it can be set from outside a class. Eg: IExtensionManager is a Seam