SlideShare a Scribd company logo
Unit Testing
Concepts, Tools and Best Practices
“I don’t have time to write tests
because I am too busy debugging.”
Why is TDD important?
 Many projects fail because they lack a good testing
methodology.
 
 It’s common sense, but it isn’t common practice.
 The sense of continuous reliability and success gives you
a feeling of confidence in your code, which makes
programming more fun.
Types of Software Testing
The Concept of Unit Testing
 A unit test is code written by a developer that tests as
small a piece of functionality (the unit) as possible.
 One function may have multiple unit tests according to
the usage and outputs of the function.
 Tests ensure
 The code meets expectations and specifications: Does what it
says it should do.
 The code continues to meet expectations over time:Avoiding
regression.
Unit Test Hierarchy
One per assembly
One per class
One per unit (not
necessarily per method)
Structure of A Unit Test
 Setup
 Prepare an input
 Call a method
 Check an output
 Tear down
Test Assertions
 Assertions are the ‘checks’ that you may perform to
determine if a test passes or fails.
 For instance:
 Assert.IsTrue()
 Assert.IsNull()
 Assert.AreEqual()
 Generally speaking, you want ONE assertion per test.
Unit Testing vs. Integration Testing
Business
Entity
Data
Layer
Data
Access
Layer
User
Interface
Unit Testing tests one layer
Integration Testing tests across layers.
Unit Testing with Mocks
Business
Entity
Data
Layer
Data
Access
Layer
Unit Testing tests one layer
A Mock allows a dependency to
be imitated so the Unit test can
be isolated.
Executing Tests
Manually:
1. Compile Test project (to .dll or .exe)
2. Open in Test runner.
3. Select and execute tests.
Automatically:
1. Build server compiles and runs tests as part of nightly
build operation.
2. Any test failures = entire build fails.
Unit Testing and Mocks
…with Mocks
Mock Library
In Isolation
Unit Testing
Replace
Dependencies…
Dependency
Injection
Framework
Automatic
Unit Testing
Framework
nUnit
mbUnit
xUnit.Net
VS TestTools
By hand
Spring.Net
Castle/Windsor
Unity
StructureMap
Mock
EasyMock
Rhino.Mocks
TypeMock
Continuous
Integration
TFS
Team City
Sample Unit Test
Best Practices
Unit Test Best Practices
Unit Test Best Practices
Unit Test Best Practices
Single Responsibility
 One test should be responsible for one scenario only.
 Test behavior, not methods:
 One method, multiple behaviors  Multiple tests
 One behavior, multiple methods  One test
Single Responsibility
void TestMethod()
{
Assert.IsTrue(behavior1)
Assert.IsTrue(behavior2)
Assert.IsTrue(behavior3)
}
void TestMethodCheckBehavior1()
{
Assert.IsTrue(behavior1)
}
void TestMethodCheckBehavior2()
{
Assert.IsTrue(behavior2)
}
void TestMethodCheckBehavior3()
{
Assert.IsTrue(behavior3)
}
Unit Test Best Practices
Self Descriptive
 Unit test must be easy to read and understand
 Variable Names
 Method Names
 Class Names
 No conditional logic
 No loops
 Name tests to represent PASS conditions:
 Public void CanMakeReservation()
 Public void TotalBillEqualsSumOfMenuItemPrices()
Self descriptive
Unit Test Best Practices
No conditional logic or loops
 Test should have no uncertainty:
 All inputs should be known
 Method behavior should be predictable
 Expected output should be strictly defined
 Split in to two tests rather than using “If” or “Case”
 Tests should not contain “While”,“Do While” or “For”
loops.
 If test logic has to be repeated, it probably means the test is
too complicated.
 Call method multiple times rather than looping inside of
method.
No conditional logic or loops
void TestBeforeOrAfter()
{
if (before)
{
Assert.IsTrue(behavior1)
}
else if (after)
{
Assert.IsTrue(behavior2)
}
else
{ Assert.IsTrue(behavior3)
}
}
void TestBefore()
{
var before = true
Assert.IsTrue(behavior1)
}
void TestAfter()
{
var after = true
Assert.IsTrue(behavior2)
}
void TestNow()
{
var before = false
var after = false
Assert.IsTrue(behavior3)
}
Unit Test Best Practices
No Exception Handling
 Indicate expected exception with attribute.
 Catch only the expected type of exception.
 Fail test if expected exception is not caught.
 Let other exceptions go uncaught.
No Exception Handling
[Test, ExpectedException(typeof(NullReferenceException))]_
Void TestException()
{
myMethod(parameter)
Assert.Fail(“MyException expected.”)
}
Unit Test Best Practices
Informative Assertion Messages
 By reading the assertion message, one should know why
the test failed and what to do.
 Include business logic information in the assertion
message (such as input values, etc.)
 Good assertion messages:
 Improve documentation of the code,
 Inform developers about the problem if the test fails.
Unit Test Best Practices
No test logic in Production Code
 Separate Unit tests and Production code in separate
projects.
 Do not create Methods or Properties used only by unit
tests.
 Use Dependency Injection or Mocks to isolate
Production code.
Unit Test Best Practices
Separation per Business Module
 Create separate test project for every layer or assembly
 Decrease execution time of test suites by splitting in to
smaller suites
 Suite 1 - All Factories
 Suite II - All Controllers
 Smaller Suites can be executed more frequently
Unit Test Best Practices
Separation per Type
 Align Test Fixtures with type definitions.
 Reminder: Unit tests are separate from integration tests!
 Different purpose
 Different frequency
 Different time of execution
 Different action in case of failure
Use AAA Pattern and Naming conversion
 Arrange-Act-Assert (AAA) Pattern
 Arrange: This is includes any initialization of dependencies,
mocks and data needed for the test to run.Different time of
execution
 Act: Invoke the code under test
 Assert: Specify the pass criteria for the test, which fails it if
not met.
Q & A

More Related Content

What's hot

Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
Valerio Maggio
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
Derek Smith
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
Francesco Garavaglia
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
Mike Lively
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Sergey Podolsky
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
kgayda
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionAlex Su
 
Software testing basics and its types
Software testing basics and its typesSoftware testing basics and its types
Software testing basics and its types
360logica Software Testing Services (A Saksoft Company)
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
alessiopace
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Scott Leberknight
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
Frank Appel
 
New Features Of Test Unit 2.x
New Features Of Test Unit 2.xNew Features Of Test Unit 2.x
New Features Of Test Unit 2.x
djberg96
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test PresentationSayedur Rahman
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Jacinto Limjap
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
ikhwanhayat
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
Dave Bouwman
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
Devvrat Shukla
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
Nayanda Haberty
 

What's hot (20)

Unit testing with Junit
Unit testing with JunitUnit testing with Junit
Unit testing with Junit
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010.Net Unit Testing with Visual Studio 2010
.Net Unit Testing with Visual Studio 2010
 
Java Unit Test and Coverage Introduction
Java Unit Test and Coverage IntroductionJava Unit Test and Coverage Introduction
Java Unit Test and Coverage Introduction
 
Software testing basics and its types
Software testing basics and its typesSoftware testing basics and its types
Software testing basics and its types
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible MistakesRoy Osherove on Unit Testing Good Practices and Horrible Mistakes
Roy Osherove on Unit Testing Good Practices and Horrible Mistakes
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Clean Unit Test Patterns
Clean Unit Test PatternsClean Unit Test Patterns
Clean Unit Test Patterns
 
New Features Of Test Unit 2.x
New Features Of Test Unit 2.xNew Features Of Test Unit 2.x
New Features Of Test Unit 2.x
 
Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test Presentation
 
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012Unit testing, UI testing and Test Driven Development in Visual Studio 2012
Unit testing, UI testing and Test Driven Development in Visual Studio 2012
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit Testing 101
Unit Testing 101Unit Testing 101
Unit Testing 101
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Java Unit Testing
Java Unit TestingJava Unit Testing
Java Unit Testing
 

Similar to Unit testing

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
UTC Fire & Security
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
Facundo Farias
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
Mohamed Taman
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
Priya Sharma
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
priya_trivedi
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
Adam Stephensen
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
Amit Choudhary
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
Attila Bertók
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
Amr E. Mohamed
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Avinash Kadam
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
Anuj Arora
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
Roman Okolovich
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
Alejandro Claro Mosqueda
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
Ahmed M. Gomaa
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
John Blum
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
Knoldus Inc.
 

Similar to Unit testing (20)

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
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.Unit testing & TDD concepts with best practice guidelines.
Unit testing & TDD concepts with best practice guidelines.
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
Why unit testingl
Why unit testinglWhy unit testingl
Why unit testingl
 
Why Unit Testingl
Why Unit TestinglWhy Unit Testingl
Why Unit Testingl
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Unit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual StudioUnit testing basics with NUnit and Visual Studio
Unit testing basics with NUnit and Visual Studio
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit tests and TDD
Unit tests and TDDUnit tests and TDD
Unit tests and TDD
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Unit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptxUnit Testing in .NET Core 7.0 with XUnit.pptx
Unit Testing in .NET Core 7.0 with XUnit.pptx
 

Recently uploaded

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
XfilesPro
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
MayankTawar1
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
Jelle | Nordend
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 

Recently uploaded (20)

Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 

Unit testing

  • 1. Unit Testing Concepts, Tools and Best Practices
  • 2. “I don’t have time to write tests because I am too busy debugging.”
  • 3.
  • 4.
  • 5. Why is TDD important?  Many projects fail because they lack a good testing methodology.    It’s common sense, but it isn’t common practice.  The sense of continuous reliability and success gives you a feeling of confidence in your code, which makes programming more fun.
  • 7. The Concept of Unit Testing  A unit test is code written by a developer that tests as small a piece of functionality (the unit) as possible.  One function may have multiple unit tests according to the usage and outputs of the function.  Tests ensure  The code meets expectations and specifications: Does what it says it should do.  The code continues to meet expectations over time:Avoiding regression.
  • 8. Unit Test Hierarchy One per assembly One per class One per unit (not necessarily per method)
  • 9. Structure of A Unit Test  Setup  Prepare an input  Call a method  Check an output  Tear down
  • 10. Test Assertions  Assertions are the ‘checks’ that you may perform to determine if a test passes or fails.  For instance:  Assert.IsTrue()  Assert.IsNull()  Assert.AreEqual()  Generally speaking, you want ONE assertion per test.
  • 11. Unit Testing vs. Integration Testing Business Entity Data Layer Data Access Layer User Interface Unit Testing tests one layer Integration Testing tests across layers.
  • 12. Unit Testing with Mocks Business Entity Data Layer Data Access Layer Unit Testing tests one layer A Mock allows a dependency to be imitated so the Unit test can be isolated.
  • 13. Executing Tests Manually: 1. Compile Test project (to .dll or .exe) 2. Open in Test runner. 3. Select and execute tests. Automatically: 1. Build server compiles and runs tests as part of nightly build operation. 2. Any test failures = entire build fails.
  • 14. Unit Testing and Mocks …with Mocks Mock Library In Isolation Unit Testing Replace Dependencies… Dependency Injection Framework Automatic Unit Testing Framework nUnit mbUnit xUnit.Net VS TestTools By hand Spring.Net Castle/Windsor Unity StructureMap Mock EasyMock Rhino.Mocks TypeMock Continuous Integration TFS Team City
  • 17. Unit Test Best Practices
  • 18. Unit Test Best Practices
  • 19. Unit Test Best Practices
  • 20. Single Responsibility  One test should be responsible for one scenario only.  Test behavior, not methods:  One method, multiple behaviors  Multiple tests  One behavior, multiple methods  One test
  • 21. Single Responsibility void TestMethod() { Assert.IsTrue(behavior1) Assert.IsTrue(behavior2) Assert.IsTrue(behavior3) } void TestMethodCheckBehavior1() { Assert.IsTrue(behavior1) } void TestMethodCheckBehavior2() { Assert.IsTrue(behavior2) } void TestMethodCheckBehavior3() { Assert.IsTrue(behavior3) }
  • 22. Unit Test Best Practices
  • 23. Self Descriptive  Unit test must be easy to read and understand  Variable Names  Method Names  Class Names  No conditional logic  No loops  Name tests to represent PASS conditions:  Public void CanMakeReservation()  Public void TotalBillEqualsSumOfMenuItemPrices() Self descriptive
  • 24. Unit Test Best Practices
  • 25. No conditional logic or loops  Test should have no uncertainty:  All inputs should be known  Method behavior should be predictable  Expected output should be strictly defined  Split in to two tests rather than using “If” or “Case”  Tests should not contain “While”,“Do While” or “For” loops.  If test logic has to be repeated, it probably means the test is too complicated.  Call method multiple times rather than looping inside of method.
  • 26. No conditional logic or loops void TestBeforeOrAfter() { if (before) { Assert.IsTrue(behavior1) } else if (after) { Assert.IsTrue(behavior2) } else { Assert.IsTrue(behavior3) } } void TestBefore() { var before = true Assert.IsTrue(behavior1) } void TestAfter() { var after = true Assert.IsTrue(behavior2) } void TestNow() { var before = false var after = false Assert.IsTrue(behavior3) }
  • 27. Unit Test Best Practices
  • 28. No Exception Handling  Indicate expected exception with attribute.  Catch only the expected type of exception.  Fail test if expected exception is not caught.  Let other exceptions go uncaught.
  • 29. No Exception Handling [Test, ExpectedException(typeof(NullReferenceException))]_ Void TestException() { myMethod(parameter) Assert.Fail(“MyException expected.”) }
  • 30. Unit Test Best Practices
  • 31. Informative Assertion Messages  By reading the assertion message, one should know why the test failed and what to do.  Include business logic information in the assertion message (such as input values, etc.)  Good assertion messages:  Improve documentation of the code,  Inform developers about the problem if the test fails.
  • 32. Unit Test Best Practices
  • 33. No test logic in Production Code  Separate Unit tests and Production code in separate projects.  Do not create Methods or Properties used only by unit tests.  Use Dependency Injection or Mocks to isolate Production code.
  • 34. Unit Test Best Practices
  • 35. Separation per Business Module  Create separate test project for every layer or assembly  Decrease execution time of test suites by splitting in to smaller suites  Suite 1 - All Factories  Suite II - All Controllers  Smaller Suites can be executed more frequently
  • 36. Unit Test Best Practices
  • 37. Separation per Type  Align Test Fixtures with type definitions.  Reminder: Unit tests are separate from integration tests!  Different purpose  Different frequency  Different time of execution  Different action in case of failure
  • 38. Use AAA Pattern and Naming conversion  Arrange-Act-Assert (AAA) Pattern  Arrange: This is includes any initialization of dependencies, mocks and data needed for the test to run.Different time of execution  Act: Invoke the code under test  Assert: Specify the pass criteria for the test, which fails it if not met.
  • 39. Q & A