SlideShare a Scribd company logo
1 of 41
Unit Testing
Concepts, Tools and Best Practices
“I don’t have time to write tests
because I am too busy
debugging.”
Types of Software Testing
Unit Testing (do
the parts perform
correctly alone?)
Integration Testing
(do the parts
perform correctly
together?)
User Acceptance
Testing (does the
system meet the
end user’s
expectations?)
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 Testing Tools
Production
Code
Unit Test
Code
Test
Runner
Unit Testing Tools
 Testing Frameworks
 NUnit
 Test Runner
 GUI
 Command line
 Automation
 CruiseControl.NET
Unit Test Hierarchy
Test Project
Test
Fixture
Test Test Test Test
Test
Fixture
Test Test Test Test
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.IsInstance()
 Assert.AreEqual()
 Generally speaking, you want ONE assertion per
test.
Unit Testing vs. Integration Testing
Busines
s Entity
Data
Layer
Data
Access
Layer
User
Interfac
e
Unit Testing tests one layer
Integration Testing tests across layers.
Unit Testing with Mocks
Busines
s 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.
Sample Unit Test
Best Practices
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
Consistent
 Multiple runs of the test should consistently return
true or consistently return false, provided no
changes were made on code
Code that can cause problems:
Dim currentDate as Date = Now()
Dim value as Integer = New Random().Next
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
Atomic
 Only two possible results: PASS or FAIL
 No partially successful tests.
 Isolation of tests:
 Different execution order must yield same results.
 Test B should not depend on outcome of Test A
 Use Mocks instead.
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
Sub TestMethod()
Assert.IsTrue(behavior1)
Assert.IsTrue(behavior2)
Assert.IsTrue(behavior3)
End Sub
Sub TestMethodCheckBehavior1()
Assert.IsTrue(behavior1)
End Sub
Sub TestMethodCheckBehavior2()
Assert.IsTrue(behavior2)
End Sub
Sub TestMethodCheckBehavior3()
Assert.IsTrue(behavior3)
End Sub
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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 Sub CanMakeReservation()
 Public Sub TotalBillEqualsSumOfMenuItemPrices()
Self descriptive
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic
or loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
Sub TestBeforeOrAfter()
If before Then
Assert.IsTrue(behavior1)
ElseIf after Then
Assert.IsTrue(behavior2)
Else
Assert.IsTrue(behavior3)
End If
End Sub
Sub TestBefore()
Dim before as Boolean = true
Assert.IsTrue(behavior1)
End Sub
Sub TestAfter()
Dim after as Boolean = true
Assert.IsTrue(behavior2)
End Sub
Sub TestNow()
Dim before as Boolean = false
Dim after as Boolean = false
Assert.IsTrue(behavior3)
End Sub
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception
handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
<ExpectedException(“MyException”)> _
Sub TestException()
myMethod(parameter)
Assert.Fail(“MyException expected.”)
End Sub
Unit Test Best Practices
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
1. Consistent
2. Atomic
3. Single Responsibility
4. Self-descriptive
5. No conditional logic or
loops
6. No exception handling
7. Informative Assertion
messages
8. No test logic in
production code
9. Separation per
business module
10. Separation per type
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
 Images from Flickr
 Best practices from www.nickokiss.com

More Related Content

What's hot

Unit Test Presentation
Unit Test PresentationUnit Test Presentation
Unit Test PresentationSayedur Rahman
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With PythonSiddhi
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)nedirtv
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development CodeOps Technologies LLP
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practicesnickokiss
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkOnkar Deshpande
 
Automated Testing with Agile
Automated Testing with AgileAutomated Testing with Agile
Automated Testing with AgileKen McCorkell
 
So you think you can write a test case
So you think you can write a test caseSo you think you can write a test case
So you think you can write a test caseSrilu Balla
 

What's hot (20)

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
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 
Unit testing
Unit testing Unit testing
Unit testing
 
Testing
TestingTesting
Testing
 
Python unit testing
Python unit testingPython unit testing
Python unit testing
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Test Driven Development With Python
Test Driven Development With PythonTest Driven Development With Python
Test Driven Development With Python
 
TDD (Test Driven Design)
TDD (Test Driven Design)TDD (Test Driven Design)
TDD (Test Driven Design)
 
TDD - Agile
TDD - Agile TDD - Agile
TDD - Agile
 
An Introduction to Test Driven Development
An Introduction to Test Driven Development An Introduction to Test Driven Development
An Introduction to Test Driven Development
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Automated Testing with Agile
Automated Testing with AgileAutomated Testing with Agile
Automated Testing with Agile
 
Unit test
Unit testUnit test
Unit test
 
So you think you can write a test case
So you think you can write a test caseSo you think you can write a test case
So you think you can write a test case
 

Similar to Unit Testing Concepts and Best Practices

Similar to Unit Testing Concepts and Best Practices (20)

Unit testing
Unit testingUnit testing
Unit testing
 
SE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and JunitSE2_Lec 21_ TDD and Junit
SE2_Lec 21_ TDD and Junit
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 
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
 
TDD Best Practices
TDD Best PracticesTDD Best Practices
TDD Best Practices
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
Google test training
Google test trainingGoogle test training
Google test training
 
TDD - Unit Testing
TDD - Unit TestingTDD - Unit Testing
TDD - Unit Testing
 
Software Testing Tecniques
Software Testing TecniquesSoftware Testing Tecniques
Software Testing Tecniques
 
Test Driven
Test DrivenTest Driven
Test Driven
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
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
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Test automation engineer
Test automation engineerTest automation engineer
Test automation engineer
 

More from Derek Smith

Robot Chickens! How a Netduino runs our backyard chicken coop
Robot Chickens!  How a Netduino runs our backyard chicken coopRobot Chickens!  How a Netduino runs our backyard chicken coop
Robot Chickens! How a Netduino runs our backyard chicken coopDerek Smith
 
Creating a Content Strategy for your Personal Brand
Creating a Content Strategy for your Personal BrandCreating a Content Strategy for your Personal Brand
Creating a Content Strategy for your Personal BrandDerek Smith
 
What's New in ASP.NET Identity - TRINUG Sept 2014
What's New in ASP.NET Identity - TRINUG Sept 2014What's New in ASP.NET Identity - TRINUG Sept 2014
What's New in ASP.NET Identity - TRINUG Sept 2014Derek Smith
 
Building data driven mobile apps with phone gap and webapi
Building data driven mobile apps with phone gap and webapiBuilding data driven mobile apps with phone gap and webapi
Building data driven mobile apps with phone gap and webapiDerek Smith
 
Managing Projects With HomeSpot
Managing Projects With HomeSpotManaging Projects With HomeSpot
Managing Projects With HomeSpotDerek Smith
 
Getting Started With HomeSpot HQ
Getting Started With HomeSpot HQGetting Started With HomeSpot HQ
Getting Started With HomeSpot HQDerek Smith
 

More from Derek Smith (6)

Robot Chickens! How a Netduino runs our backyard chicken coop
Robot Chickens!  How a Netduino runs our backyard chicken coopRobot Chickens!  How a Netduino runs our backyard chicken coop
Robot Chickens! How a Netduino runs our backyard chicken coop
 
Creating a Content Strategy for your Personal Brand
Creating a Content Strategy for your Personal BrandCreating a Content Strategy for your Personal Brand
Creating a Content Strategy for your Personal Brand
 
What's New in ASP.NET Identity - TRINUG Sept 2014
What's New in ASP.NET Identity - TRINUG Sept 2014What's New in ASP.NET Identity - TRINUG Sept 2014
What's New in ASP.NET Identity - TRINUG Sept 2014
 
Building data driven mobile apps with phone gap and webapi
Building data driven mobile apps with phone gap and webapiBuilding data driven mobile apps with phone gap and webapi
Building data driven mobile apps with phone gap and webapi
 
Managing Projects With HomeSpot
Managing Projects With HomeSpotManaging Projects With HomeSpot
Managing Projects With HomeSpot
 
Getting Started With HomeSpot HQ
Getting Started With HomeSpot HQGetting Started With HomeSpot HQ
Getting Started With HomeSpot HQ
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Unit Testing Concepts and Best Practices

  • 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. Types of Software Testing Unit Testing (do the parts perform correctly alone?) Integration Testing (do the parts perform correctly together?) User Acceptance Testing (does the system meet the end user’s expectations?)
  • 6. 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 Testing Tools  Testing Frameworks  NUnit  Test Runner  GUI  Command line  Automation  CruiseControl.NET
  • 9. Unit Test Hierarchy Test Project Test Fixture Test Test Test Test Test Fixture Test Test Test Test One per assembly One per class One per unit (not necessarily per method)
  • 10. Structure of A Unit Test  Setup  Prepare an input  Call a method  Check an output  Tear down
  • 11. Test Assertions  Assertions are the ‘checks’ that you may perform to determine if a test passes or fails.  For instance:  Assert.IsTrue()  Assert.IsInstance()  Assert.AreEqual()  Generally speaking, you want ONE assertion per test.
  • 12. Unit Testing vs. Integration Testing Busines s Entity Data Layer Data Access Layer User Interfac e Unit Testing tests one layer Integration Testing tests across layers.
  • 13. Unit Testing with Mocks Busines s 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.
  • 14. 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.
  • 17. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 18. Consistent  Multiple runs of the test should consistently return true or consistently return false, provided no changes were made on code Code that can cause problems: Dim currentDate as Date = Now() Dim value as Integer = New Random().Next
  • 19. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 20. Atomic  Only two possible results: PASS or FAIL  No partially successful tests.  Isolation of tests:  Different execution order must yield same results.  Test B should not depend on outcome of Test A  Use Mocks instead.
  • 21. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 22. 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
  • 23. Single Responsibility Sub TestMethod() Assert.IsTrue(behavior1) Assert.IsTrue(behavior2) Assert.IsTrue(behavior3) End Sub Sub TestMethodCheckBehavior1() Assert.IsTrue(behavior1) End Sub Sub TestMethodCheckBehavior2() Assert.IsTrue(behavior2) End Sub Sub TestMethodCheckBehavior3() Assert.IsTrue(behavior3) End Sub
  • 24. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 25. 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 Sub CanMakeReservation()  Public Sub TotalBillEqualsSumOfMenuItemPrices() Self descriptive
  • 26. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 27. 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.
  • 28. No conditional logic or loops Sub TestBeforeOrAfter() If before Then Assert.IsTrue(behavior1) ElseIf after Then Assert.IsTrue(behavior2) Else Assert.IsTrue(behavior3) End If End Sub Sub TestBefore() Dim before as Boolean = true Assert.IsTrue(behavior1) End Sub Sub TestAfter() Dim after as Boolean = true Assert.IsTrue(behavior2) End Sub Sub TestNow() Dim before as Boolean = false Dim after as Boolean = false Assert.IsTrue(behavior3) End Sub
  • 29. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 30. 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.
  • 31. No Exception Handling <ExpectedException(“MyException”)> _ Sub TestException() myMethod(parameter) Assert.Fail(“MyException expected.”) End Sub
  • 32. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 33. 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.
  • 34. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 35. 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.
  • 36. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 37. 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
  • 38. Unit Test Best Practices 1. Consistent 2. Atomic 3. Single Responsibility 4. Self-descriptive 5. No conditional logic or loops 6. No exception handling 7. Informative Assertion messages 8. No test logic in production code 9. Separation per business module 10. Separation per type
  • 39. 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
  • 40.
  • 41.  Images from Flickr  Best practices from www.nickokiss.com