SlideShare una empresa de Scribd logo
1 de 40
Descargar para leer sin conexión
Database Unit Testing
Fundamentals
Eric Selje
Eric Selje
 Database Developer Since 1985
 dBase/FoxBase/FoxPro since 1986
 .Net / SQL Server more recently
 Salty Dog Solutions, LLC (Consulting)
 Mobile
 Web
 Database
 Legacy
 US Courts
 User Groups
 MadFox since 1995
 Geek Lunch
Agenda
 What is “Unit Testing”
 What does it mean to “Unit Test” a
database?
 How to do it in SSMS
 Manually coding
 tSQLt Framework
 SQL Test
What is “Unit Testing”
 Code that exercises a specific portion of
your codebase in a particular context.
 Returns a simple pass/fail based on an
expected known result.
 Inspect the results to know how things
stand and possibly act on it.
Simple Sample Tests
 Does that scalar function work as
expected?
 Does that stored procedure …
 Does the trigger fire properly?
 Does that constraint prevent me from
inserting bad data?
Goals
 Catch mistakes as early in the process as
possible.
Goals
 Keep your units of code as small and
testable as possible.
 Tighter, more maintainable code
Goals
 Ensure that you have a good idea what
the code is supposed to do before you
write it.
Goals
 They give you confidence that your code
works as you expect it to work.
Bonus Goals
Can ensure CONFORMITY with Standards
What to Test?
 Not possible to test everything
 75% coverage a fine goal
 Multiple tests for each piece of code
 Normal Conditions
 Edge Conditions
 Null / Empty parameters
 Out of bound conditions
Downsides with Unit Testing
 More up-front time / work
 Less instant gratification
 Pays off on the back end
 Hard to justify to upper management
 “Squishy”
 Can’t prove it worked
Unit Testing is NOT….
 Integration Testing in which we make sure
our individual modules work well together.
 Does the 'Delete' button on the U/I actually invoke the 'Delete' method
in the ORM properly and handle the result?
 Does calling the 'Delete' method in the ORM actually remove a record
from the database?
Unit Testing is NOT ….
 System Testing, when you deliver your app
to the testers and they check it all out to
make sure it meets the requirements. Eg.
 Load testing
 Compatibility testing
 Accessibility testing
 Acceptance testing
 and many more…
Unit Testing is…
 Peace
 of
 Mind
What does this have to do with
DATABASES?
There’s code in them thar databases
 Stored procedures
 Functions
 Constraints
 Views
 Scripts
 …and more…
Example #1
 Write a unit test to ensure our scalar
function returns what we think it should.
 Also, make sure it doesn’t return what we
don’t think it should. Test edge cases.
Example #2
 Write multiple unit tests for a function…
Example #3
 How to test constraints?
 Embed in a TRANSACTION
 Try to add some bad data
 See if it threw an error
 End TRANSACTION
Example #4a - Views
Old way of testing
1. Alter a view
2. Run view
3. Got data? Good to go!
Example #4b - Views
How to test if a View’s data went bad?
1. You’d have to have ‘saved’ a copy of your
view data before you make changes.
2. Make your changes
3. Get your new view data
4. Compare (um…how to do that?)
This is getting out of hand!
 We could write the unit tests in Visual Studio
 nUnit
 Sql Server Data Tools
 Requires a separate tool which we may not
have.
 It'd be nice if there was a framework for
writing unit tests that allowed us to remain
within SQL Server Management Studio.
tSQLt Framework
 http://tsqlt.org/
 tSQLt is a database unit testing framework
for Microsoft SQL Server.
 Features:
 Test are run within transactions
 Tests are grouped within a schema
 Output can go to a file that a CI tool can use
 …and more
tSQLt Framework Installation
1. Download zip
2. Add scripts to a project (optional)
Comes w/ an example database…
Adding tSql to your database
1. Prep your database
1. ALTER AUTHORIZATION ON DATABASE TO
sa (Maybe)
2. SET TRUSTWORTHY ON
2. Run tSqlt.class script
on each database to test
Redo our tests in tSQLt
 Create a test class: tSQLt.NewTestClass
 Creates a new schema with that classname
 Create a test: CREATE PROCEDURE
 Schema should be the new class name
 Prefix the sp name with ‘test’
 Run the Test: tsqlt.Run <testName>
Assert Yourself
 AssertEquals
 AssertLike
 % or _
 AssertEqualsString
 Varchar(Max) comparisons
Assert Yourself
 AssertEqualsTable
 AssertResultSetsHaveSameMetaData
 FakeTable (remove constraints)
Assert Yourself
AssertObjectExists
Run All Tests in a Class
 One test per stored procedure
 tsqlt.RunTestClass <className>
 tsqlt.RunAll
Faking It
 FakeTable
Tips
 Filter the Stored Procedures to just see Tests
 Assign a hotkey to run tests (Tools, Options,
Environment, Keyboard,
EXEC tSQLt.RunAll; --)
 Create a template for creating a test
(thanks, @SQLAgentMan)
Not Enough?
 No Pretty Color Coding?
 I can't just doubleclick on my failed test to
edit it? Waah?
“SQL Test”
 RedGate
 Not Free
 $295 Standalone
 $1495 in SQL Developer Bundle
 SQL Source Control
 Continuous Integration
 Except for one lucky attendee at #SQLSat206
SQL Test
Gets you
• Nice GUI
• Color Coding
• SQL Cop Tests
Demo…
Continuous Integration
 Automatically run Unit Tests
 On a schedule
 When code is checked in
 Reject if fails
 Proceed with other tests if succeeds
 Compile the app
 Distribute
Conclusion
 Unit Testing is for Database People
 Discipline you to write testable code
 Reward you with easy to maintain code
 Fewer errors
 Save money
 Save time
 Conform to standards
Q&A / Comments
 What else would you consider testing?
Resources
 Unit Testing Database with tSQLt
 Ten Things I Wish I'd Known
 48 SQL Cop Tests (Zip File)
 Using SQL Test in Continuous Integration, by
Dave Green
 How to write good unit tests
 Are Unit Tests overused?
 Test Driven Development
Thank You!
Please fill out your evals
 Twitter: EricSelje
 LinkedIn: saltydog

Más contenido relacionado

Similar a SELJE_Database_Unit_Testing_Slides.pdf

An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testingAdam Stephensen
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tipsTypemock
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flexmichael.labriola
 
Unit testing
Unit testingUnit testing
Unit testingPiXeL16
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql ServerDavid P. Moore
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksŁukasz Morawski
 
I Smell A RAT- Rapid Application Testing
I Smell A RAT- Rapid Application TestingI Smell A RAT- Rapid Application Testing
I Smell A RAT- Rapid Application TestingPeter Presnell
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And DrupalPeter Arato
 
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
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In ActionJon Kruger
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
Automated Testing with Databases
Automated Testing with DatabasesAutomated Testing with Databases
Automated Testing with Databaseselliando dias
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
A data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonA data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonTerry Bunio
 

Similar a SELJE_Database_Unit_Testing_Slides.pdf (20)

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
 
Practical unit testing tips
Practical unit testing tipsPractical unit testing tips
Practical unit testing tips
 
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in FlexassertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
assertYourself - Breaking the Theories and Assumptions of Unit Testing in Flex
 
Unit testing
Unit testingUnit testing
Unit testing
 
Test Driven Development with Sql Server
Test Driven Development with Sql ServerTest Driven Development with Sql Server
Test Driven Development with Sql Server
 
TDD Workshop UTN 2012
TDD Workshop UTN 2012TDD Workshop UTN 2012
TDD Workshop UTN 2012
 
Unit test
Unit testUnit test
Unit test
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation Frameworks
 
I Smell A RAT- Rapid Application Testing
I Smell A RAT- Rapid Application TestingI Smell A RAT- Rapid Application Testing
I Smell A RAT- Rapid Application Testing
 
Testing And Drupal
Testing And DrupalTesting And Drupal
Testing And Drupal
 
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
 
Test-Driven Development In Action
Test-Driven Development In ActionTest-Driven Development In Action
Test-Driven Development In Action
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
Automated Testing with Databases
Automated Testing with DatabasesAutomated Testing with Databases
Automated Testing with Databases
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Unit testing - An introduction
Unit testing - An introductionUnit testing - An introduction
Unit testing - An introduction
 
A data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonA data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madison
 
Unit testing
Unit testingUnit testing
Unit testing
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 

Más de Eric Selje

SELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptxSELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptxEric Selje
 
SELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdfSELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdfEric Selje
 
SELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdfSELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdfEric Selje
 
SELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptxSELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptxEric Selje
 
SELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptxSELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptxEric Selje
 
SELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdfSELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdfEric Selje
 
OneNote to Rule Them All.pdf
OneNote to Rule Them All.pdfOneNote to Rule Them All.pdf
OneNote to Rule Them All.pdfEric Selje
 
FoxUnit in Depth.pptx
FoxUnit in Depth.pptxFoxUnit in Depth.pptx
FoxUnit in Depth.pptxEric Selje
 
OneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptxOneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptxEric Selje
 
Selje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdfSelje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdfEric Selje
 
Selje_SSMS for the Accidental DBA.pdf
Selje_SSMS for the Accidental DBA.pdfSelje_SSMS for the Accidental DBA.pdf
Selje_SSMS for the Accidental DBA.pdfEric Selje
 
Selje_Fox on the Run.ppt
Selje_Fox on the Run.pptSelje_Fox on the Run.ppt
Selje_Fox on the Run.pptEric Selje
 
Selje_Fox on the Run.pdf
Selje_Fox on the Run.pdfSelje_Fox on the Run.pdf
Selje_Fox on the Run.pdfEric Selje
 
Selje_Extending Web Apps.ppt
Selje_Extending Web Apps.pptSelje_Extending Web Apps.ppt
Selje_Extending Web Apps.pptEric Selje
 
Selje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfSelje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfEric Selje
 
Don't Be a Target!
Don't Be a Target! Don't Be a Target!
Don't Be a Target! Eric Selje
 
Energy audit tablet screenshots
Energy audit tablet screenshotsEnergy audit tablet screenshots
Energy audit tablet screenshotsEric Selje
 

Más de Eric Selje (17)

SELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptxSELJE - VFP and IT Security.pptx
SELJE - VFP and IT Security.pptx
 
SELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdfSELJE - VFP and IT Security.pdf
SELJE - VFP and IT Security.pdf
 
SELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdfSELJE - VFP Advanced.pdf
SELJE - VFP Advanced.pdf
 
SELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptxSELJE - VFP Advanced.pptx
SELJE - VFP Advanced.pptx
 
SELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptxSELJE - Look at X Sharp.pptx
SELJE - Look at X Sharp.pptx
 
SELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdfSELJE - Look at X Sharp.pdf
SELJE - Look at X Sharp.pdf
 
OneNote to Rule Them All.pdf
OneNote to Rule Them All.pdfOneNote to Rule Them All.pdf
OneNote to Rule Them All.pdf
 
FoxUnit in Depth.pptx
FoxUnit in Depth.pptxFoxUnit in Depth.pptx
FoxUnit in Depth.pptx
 
OneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptxOneNote to Rule Them All Slides.pptx
OneNote to Rule Them All Slides.pptx
 
Selje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdfSelje_SSMS (Slides).pdf
Selje_SSMS (Slides).pdf
 
Selje_SSMS for the Accidental DBA.pdf
Selje_SSMS for the Accidental DBA.pdfSelje_SSMS for the Accidental DBA.pdf
Selje_SSMS for the Accidental DBA.pdf
 
Selje_Fox on the Run.ppt
Selje_Fox on the Run.pptSelje_Fox on the Run.ppt
Selje_Fox on the Run.ppt
 
Selje_Fox on the Run.pdf
Selje_Fox on the Run.pdfSelje_Fox on the Run.pdf
Selje_Fox on the Run.pdf
 
Selje_Extending Web Apps.ppt
Selje_Extending Web Apps.pptSelje_Extending Web Apps.ppt
Selje_Extending Web Apps.ppt
 
Selje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdfSelje_Amazing VFP2C32 Library.pdf
Selje_Amazing VFP2C32 Library.pdf
 
Don't Be a Target!
Don't Be a Target! Don't Be a Target!
Don't Be a Target!
 
Energy audit tablet screenshots
Energy audit tablet screenshotsEnergy audit tablet screenshots
Energy audit tablet screenshots
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 

Último (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

SELJE_Database_Unit_Testing_Slides.pdf

  • 2. Eric Selje  Database Developer Since 1985  dBase/FoxBase/FoxPro since 1986  .Net / SQL Server more recently  Salty Dog Solutions, LLC (Consulting)  Mobile  Web  Database  Legacy  US Courts  User Groups  MadFox since 1995  Geek Lunch
  • 3. Agenda  What is “Unit Testing”  What does it mean to “Unit Test” a database?  How to do it in SSMS  Manually coding  tSQLt Framework  SQL Test
  • 4. What is “Unit Testing”  Code that exercises a specific portion of your codebase in a particular context.  Returns a simple pass/fail based on an expected known result.  Inspect the results to know how things stand and possibly act on it.
  • 5. Simple Sample Tests  Does that scalar function work as expected?  Does that stored procedure …  Does the trigger fire properly?  Does that constraint prevent me from inserting bad data?
  • 6. Goals  Catch mistakes as early in the process as possible.
  • 7. Goals  Keep your units of code as small and testable as possible.  Tighter, more maintainable code
  • 8. Goals  Ensure that you have a good idea what the code is supposed to do before you write it.
  • 9. Goals  They give you confidence that your code works as you expect it to work.
  • 10. Bonus Goals Can ensure CONFORMITY with Standards
  • 11. What to Test?  Not possible to test everything  75% coverage a fine goal  Multiple tests for each piece of code  Normal Conditions  Edge Conditions  Null / Empty parameters  Out of bound conditions
  • 12. Downsides with Unit Testing  More up-front time / work  Less instant gratification  Pays off on the back end  Hard to justify to upper management  “Squishy”  Can’t prove it worked
  • 13. Unit Testing is NOT….  Integration Testing in which we make sure our individual modules work well together.  Does the 'Delete' button on the U/I actually invoke the 'Delete' method in the ORM properly and handle the result?  Does calling the 'Delete' method in the ORM actually remove a record from the database?
  • 14. Unit Testing is NOT ….  System Testing, when you deliver your app to the testers and they check it all out to make sure it meets the requirements. Eg.  Load testing  Compatibility testing  Accessibility testing  Acceptance testing  and many more…
  • 15. Unit Testing is…  Peace  of  Mind
  • 16. What does this have to do with DATABASES? There’s code in them thar databases  Stored procedures  Functions  Constraints  Views  Scripts  …and more…
  • 17. Example #1  Write a unit test to ensure our scalar function returns what we think it should.  Also, make sure it doesn’t return what we don’t think it should. Test edge cases.
  • 18. Example #2  Write multiple unit tests for a function…
  • 19. Example #3  How to test constraints?  Embed in a TRANSACTION  Try to add some bad data  See if it threw an error  End TRANSACTION
  • 20. Example #4a - Views Old way of testing 1. Alter a view 2. Run view 3. Got data? Good to go!
  • 21. Example #4b - Views How to test if a View’s data went bad? 1. You’d have to have ‘saved’ a copy of your view data before you make changes. 2. Make your changes 3. Get your new view data 4. Compare (um…how to do that?)
  • 22. This is getting out of hand!  We could write the unit tests in Visual Studio  nUnit  Sql Server Data Tools  Requires a separate tool which we may not have.  It'd be nice if there was a framework for writing unit tests that allowed us to remain within SQL Server Management Studio.
  • 23. tSQLt Framework  http://tsqlt.org/  tSQLt is a database unit testing framework for Microsoft SQL Server.  Features:  Test are run within transactions  Tests are grouped within a schema  Output can go to a file that a CI tool can use  …and more
  • 24. tSQLt Framework Installation 1. Download zip 2. Add scripts to a project (optional) Comes w/ an example database…
  • 25. Adding tSql to your database 1. Prep your database 1. ALTER AUTHORIZATION ON DATABASE TO sa (Maybe) 2. SET TRUSTWORTHY ON 2. Run tSqlt.class script on each database to test
  • 26. Redo our tests in tSQLt  Create a test class: tSQLt.NewTestClass  Creates a new schema with that classname  Create a test: CREATE PROCEDURE  Schema should be the new class name  Prefix the sp name with ‘test’  Run the Test: tsqlt.Run <testName>
  • 27. Assert Yourself  AssertEquals  AssertLike  % or _  AssertEqualsString  Varchar(Max) comparisons
  • 28. Assert Yourself  AssertEqualsTable  AssertResultSetsHaveSameMetaData  FakeTable (remove constraints)
  • 30. Run All Tests in a Class  One test per stored procedure  tsqlt.RunTestClass <className>  tsqlt.RunAll
  • 32. Tips  Filter the Stored Procedures to just see Tests  Assign a hotkey to run tests (Tools, Options, Environment, Keyboard, EXEC tSQLt.RunAll; --)  Create a template for creating a test (thanks, @SQLAgentMan)
  • 33. Not Enough?  No Pretty Color Coding?  I can't just doubleclick on my failed test to edit it? Waah?
  • 34. “SQL Test”  RedGate  Not Free  $295 Standalone  $1495 in SQL Developer Bundle  SQL Source Control  Continuous Integration  Except for one lucky attendee at #SQLSat206
  • 35. SQL Test Gets you • Nice GUI • Color Coding • SQL Cop Tests Demo…
  • 36. Continuous Integration  Automatically run Unit Tests  On a schedule  When code is checked in  Reject if fails  Proceed with other tests if succeeds  Compile the app  Distribute
  • 37. Conclusion  Unit Testing is for Database People  Discipline you to write testable code  Reward you with easy to maintain code  Fewer errors  Save money  Save time  Conform to standards
  • 38. Q&A / Comments  What else would you consider testing?
  • 39. Resources  Unit Testing Database with tSQLt  Ten Things I Wish I'd Known  48 SQL Cop Tests (Zip File)  Using SQL Test in Continuous Integration, by Dave Green  How to write good unit tests  Are Unit Tests overused?  Test Driven Development
  • 40. Thank You! Please fill out your evals  Twitter: EricSelje  LinkedIn: saltydog