SlideShare a Scribd company logo
#datasatpn
February 27th, 2021
Data Saturday #1
Database development unit test
with tSQLt
Sergio Govoni
Slide and demo: https://bit.ly/37Sa4oG
https://twitter.com/hackerrank/status/607223964469846018
#datasatpn
February 27th, 2021
Data Saturday #1
A big “Thank you” to our Sponsors
Who I am
twitter.com/segovoni
linkedin.com/in/sgovoni
github.com/segovoni
Sergio Govoni
Agenda
• Introduction to Unit Testing
• Introduction to tSQLt framework
• The anatomy of a unit test
• Our first unit test
Types of database unit tests
• Structural Testing
• Functional Testing
• Non-functional Testing
What is a unit test?
• Unit testing is a software testing level that aims to test a discrete
piece of code. The “unit” refers to the smallest piece of code that can
be tested separately
• Unit test
• Must be repeatable
• Isolates the code under test from the rest of the code
• Doesn’t test how the unit interacts with other units
What is a unit test?
• Unit test have to test one question at a time and that question should
reflect a requirement for our code
• Unit testing is about confirming that all the individual parts work, not
that they work together
• Unit tests is usually written by the Development Team
System Under Test (SUT)
• In a database solution, the “unit” you want to test is typically a stored
procedure, a trigger or a user-defined function
• It is very important to define the System Under Test (SUT) first and
isolate it!
• System Under Test must not be influenced by other procedures or
functions called within the one you want to test
What does a unit test give me?
• Unit tests convey safety
• Unit tests provide documentation of the software requirements
• Unit tests are preparatory to the design phase (TDD methodology),
they force you to think how to organize properly
• Unit tests simplify the error checking process
When should I write the unit tests?
• Before starting the development?
• Focusing on the actual requirements, it minimizes the work for the Developer
• During development?
• Some tests may need to be reviewed due to development force a change in
requirements
• After completing the development?
• It’s the only option, not the optimal one, if you have already written the code
Introduction to tSQLt
• The framework tSQLt was developed by Sebastian Meine and Dennis
Lloyd, it is the open source framework for implementing unit tests in
T-SQL for SQL Server
• It works with all editions of SQL Server starting from SQL Server 2005
SP2
• It requires SQL CLR enabled
Introduction to tSQLt
• tSQLt is written in T-SQL
• It doesn’t work on Azure SQL Database, nowadays
• It works on Azure SQL Managed Instances ☺
Benefits of using tSQLt
• Unit tests will be written in T-SQL, you don’t need to learn new
programming language
• Data manipulation will be rolled back at the end of the test so you
don’t need any data cleanup
• Mock objects are supported
• tSQLt can be integrated into SSDT projects or 3rd party tools
Benefits of using tSQLt
• Tests can be grouped within a single schema
• You can use a setup routine for a group of tests or class
• The output can be in plain text or XML
tSQLt Setup: Install in your development DB
• Download tSQLt scripts from tsqlt.org/downloads
• Enable CLR at the SQL Server instance level
• In each development database you want to install tSQLt
• Enable TRUSTWORTHY property
• Execute tSQLt.class.sql
Demo
tSQLt Setup
The anatomy of a unit test
• Arrange (or Assemble)
• Preparation of data on which the test will run
• Isolation of the code from any external dependencies
• Act
• The system under test (SUT) will be executed and the output has been
acquired as a result
• Assert
• The expected result will be compared with the obtained one, the test will fail
or will have a positive outcome according to this comparison
How does a test run with tSQLt
• When we run a test through tSQLt, the framework traces the running
test and starts a dedicated transaction
• The configuration procedure for the test class will be executed (if
existing) and afterward the test will be executed
• At the end of the test, the tSQLt framework will rollback the
dedicated transaction
• The results will be stored in the tSQLt.TestResult table
Our first unit test is for a Trigger ☺
• You developed a Trigger for AdventureWorks2017 to prevent the
insertion of new products with values less than 10 as a “safety stock”
• The Company Adventure Works LTD wishes to always have a
warehouse stock of no less than 10 units for each product
• To make our trigger simple, it will only respond to the OnInsert event,
for INSERT commands
Our first unit test is for a Trigger
CREATE TRIGGER Production.TR_Product_SafetyStockLevel ON Production.Product
AFTER INSERT AS
BEGIN
/* Avoid to insert products with safety stock level lower than 10! */
DECLARE @SafetyStockLevel SMALLINT;
SELECT
@SafetyStockLevel = SafetyStockLevel
FROM
inserted;
IF (@SafetyStockLevel < 10)
BEGIN
-- Error!!
EXEC Production.usp_Raiserror_SafetyStockLevel
@Message = 'Safety stock level cannot be lower than 10!';
END;
END;
Possible test
• Try to insert one correct row
• Try to insert one wrong row and observe the error caught by the
Trigger
• Try to insert multiple rows in a single statements
• Wrong and correct rows
• Does the order matter?
• Let’s start!! ☺
Demo
Let’s write our first unit test!
Isolate dependencies
• Tests often depend on data or the result of a stored procedure or
function
• This affects our test’s repeatability
• We can’t rely on data being unchanged
• We need to isolate
• Data
• Table constraints
• Stored procedures
• Functions
Isolate stored procedures
tSQLt.SpyProcedure [@ProcedureName = ] 'procedure name'
[, [@CommandToExecute = ] 'command' ]
• It replaces the execution of the stored procedure with the
specified command
• A log table named @ProcedureName_SpyProcedureLog is
created and a new log entry is made for each fake execution
of the “spied” procedure
• https://bit.ly/2XWVZBl
Summary
• We discussed about the importance of unit testing applied to
database development
• We learn how to use tSQLt framework
• We learned how to write our first unit test using tSQLt
Think about triggers, SP and complex functions you wrote (those with
more than 200 lines of code just to be clear ☺) would you feel safe in
modifying them? If the answer is “No” the first thing to do is to write
the unit tests, now you know how!
Resources
• Articles
• What it is and why it is important for T-SQL code
• https://bit.ly/3tfUTP8
• The tSQLt framework and the execution of a test
• https://bit.ly/3oFy1Fb
• How to write your first unit test for T-SQL code
• https://bit.ly/3qkBRFq
• tSQLt - https://tsqlt.org
Resources
• Videos
• Implementare unit testing su Sql Server - Alessandro Alpi
• https://www.youtube.com/watch?v=7tIHg3P0ea0
• Continuous Deployment, portare SQL Server nel mondo DevOps - Alessandro Alpi
• https://www.youtube.com/watch?v=1jBm4MFFlPg
• Tools
• Red-Gate SQL Test
• https://www.red-gate.com/products/sql-development/sql-test/
• TSQLUnit
• https://github.com/aevdokimenko/tsqlunit
Ask your Questions
#datasatpn
February 27th, 2021
Data Saturday #1
Thanks!
#datasatpn
@segovoni
Slide and demo: https://bit.ly/37Sa4oG

More Related Content

What's hot (20)

PDF
Unit testing in xcode 8 with swift
allanh0526
 
PDF
Test Driven Development for PLSQL with utPLSQL v3
Jacek Gebal
 
ODP
Test ng
fbenault
 
PDF
Unit Tesing in iOS
Ciklum Ukraine
 
PDF
An Introduction to Unit Test Using NUnit
weili_at_slideshare
 
PPTX
TestNG Session presented in Xebia XKE
Abhishek Yadav
 
PDF
TestNg_Overview_Config
Abhishek Chakraborty
 
PDF
Test ng for testers
Colombo Selenium Meetup
 
PDF
TestNG vs. JUnit4
Andrey Oleynik
 
PDF
TestNG introduction
Denis Bazhin
 
PPTX
Junit4&testng presentation
Sanjib Dhar
 
PPTX
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
PPTX
Introduction of TestNG framework and its benefits over Junit framework
BugRaptors
 
PDF
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
PPTX
Refactoring Legacy Web Forms for Test Automation
Stephen Fuqua
 
PPTX
Generating unit tests based on user logs
Rick Wicker
 
ODP
Testing In Java
David Noble
 
PPTX
TestNG Data Binding
Matthias Rothe
 
PPTX
Avoiding test hell
Yun Ki Lee
 
Unit testing in xcode 8 with swift
allanh0526
 
Test Driven Development for PLSQL with utPLSQL v3
Jacek Gebal
 
Test ng
fbenault
 
Unit Tesing in iOS
Ciklum Ukraine
 
An Introduction to Unit Test Using NUnit
weili_at_slideshare
 
TestNG Session presented in Xebia XKE
Abhishek Yadav
 
TestNg_Overview_Config
Abhishek Chakraborty
 
Test ng for testers
Colombo Selenium Meetup
 
TestNG vs. JUnit4
Andrey Oleynik
 
TestNG introduction
Denis Bazhin
 
Junit4&testng presentation
Sanjib Dhar
 
Test NG Framework Complete Walk Through
Narendran Solai Sridharan
 
Introduction of TestNG framework and its benefits over Junit framework
BugRaptors
 
Into The Box 2018 | Assert control over your legacy applications
Ortus Solutions, Corp
 
Refactoring Legacy Web Forms for Test Automation
Stephen Fuqua
 
Generating unit tests based on user logs
Rick Wicker
 
Testing In Java
David Noble
 
TestNG Data Binding
Matthias Rothe
 
Avoiding test hell
Yun Ki Lee
 

Similar to Database development unit test with tSQLt (20)

PDF
Test Driven Development with Sql Server
David P. Moore
 
PPT
A testing framework for Microsoft SQL-Server
elliando dias
 
PPTX
#DOAW16 - DevOps@work Roma 2016 - Testing your databases
Alessandro Alpi
 
PDF
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
PPTX
Get Testing with tSQLt - SQL In The City Workshop 2014
Red Gate Software
 
PDF
Unit Testing SQL Server
Giovanni Scerra ☃
 
PDF
A data driven etl test framework sqlsat madison
Terry Bunio
 
PDF
Adding unit tests to the database deployment pipeline
Eduardo Piairo
 
PDF
SQLDay 2017 - Database Unit Tests with tSQLt
Marek Maśko
 
PDF
Adding unit tests with tSQLt to the database deployment pipeline
Eduardo Piairo
 
PDF
Adding unit tests to the database deployment pipeline
Eduardo Piairo
 
PDF
Adding unit tests with tSQLt to the database deployment pipeline
Eduardo Piairo
 
PDF
Adding unit tests with tSQLt to the database deployment pipeline
Eduardo Piairo
 
PPTX
tSQLt Database Unit Testing
Dexter Baga
 
PPTX
Database Unit Testing Made Easy with VSTS
Sanil Mhatre
 
PDF
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
Jacek Gebal
 
PPTX
utPLSQL: Unit Testing for Oracle PL/SQL
Steven Feuerstein
 
PPT
xUnit Style Database Testing
Chris Oldwood
 
PDF
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
Jacek Gebal
 
PDF
Agile db testing_techniques
Tarik Essawi
 
Test Driven Development with Sql Server
David P. Moore
 
A testing framework for Microsoft SQL-Server
elliando dias
 
#DOAW16 - DevOps@work Roma 2016 - Testing your databases
Alessandro Alpi
 
SELJE_Database_Unit_Testing_Slides.pdf
Eric Selje
 
Get Testing with tSQLt - SQL In The City Workshop 2014
Red Gate Software
 
Unit Testing SQL Server
Giovanni Scerra ☃
 
A data driven etl test framework sqlsat madison
Terry Bunio
 
Adding unit tests to the database deployment pipeline
Eduardo Piairo
 
SQLDay 2017 - Database Unit Tests with tSQLt
Marek Maśko
 
Adding unit tests with tSQLt to the database deployment pipeline
Eduardo Piairo
 
Adding unit tests to the database deployment pipeline
Eduardo Piairo
 
Adding unit tests with tSQLt to the database deployment pipeline
Eduardo Piairo
 
Adding unit tests with tSQLt to the database deployment pipeline
Eduardo Piairo
 
tSQLt Database Unit Testing
Dexter Baga
 
Database Unit Testing Made Easy with VSTS
Sanil Mhatre
 
prohuddle-utPLSQL v3 - Ultimate unit testing framework for Oracle
Jacek Gebal
 
utPLSQL: Unit Testing for Oracle PL/SQL
Steven Feuerstein
 
xUnit Style Database Testing
Chris Oldwood
 
POUG Meetup 1st MArch 2019 - utPLSQL v3 - Testing Framework for PL/SQL
Jacek Gebal
 
Agile db testing_techniques
Tarik Essawi
 
Ad

Recently uploaded (20)

PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PPTX
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
PDF
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
PDF
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Agentic Automation Journey Series Day 2 – Prompt Engineering for UiPath Agents
klpathrudu
 
MiniTool Partition Wizard Free Crack + Full Free Download 2025
bashirkhan333g
 
HiHelloHR – Simplify HR Operations for Modern Workplaces
HiHelloHR
 
Tally software_Introduction_Presentation
AditiBansal54083
 
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...
Lingwen1998
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Unlock Efficiency with Insurance Policy Administration Systems
Insurance Tech Services
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
Ad

Database development unit test with tSQLt

  • 1. #datasatpn February 27th, 2021 Data Saturday #1 Database development unit test with tSQLt Sergio Govoni Slide and demo: https://bit.ly/37Sa4oG https://twitter.com/hackerrank/status/607223964469846018
  • 2. #datasatpn February 27th, 2021 Data Saturday #1 A big “Thank you” to our Sponsors
  • 4. Agenda • Introduction to Unit Testing • Introduction to tSQLt framework • The anatomy of a unit test • Our first unit test
  • 5. Types of database unit tests • Structural Testing • Functional Testing • Non-functional Testing
  • 6. What is a unit test? • Unit testing is a software testing level that aims to test a discrete piece of code. The “unit” refers to the smallest piece of code that can be tested separately • Unit test • Must be repeatable • Isolates the code under test from the rest of the code • Doesn’t test how the unit interacts with other units
  • 7. What is a unit test? • Unit test have to test one question at a time and that question should reflect a requirement for our code • Unit testing is about confirming that all the individual parts work, not that they work together • Unit tests is usually written by the Development Team
  • 8. System Under Test (SUT) • In a database solution, the “unit” you want to test is typically a stored procedure, a trigger or a user-defined function • It is very important to define the System Under Test (SUT) first and isolate it! • System Under Test must not be influenced by other procedures or functions called within the one you want to test
  • 9. What does a unit test give me? • Unit tests convey safety • Unit tests provide documentation of the software requirements • Unit tests are preparatory to the design phase (TDD methodology), they force you to think how to organize properly • Unit tests simplify the error checking process
  • 10. When should I write the unit tests? • Before starting the development? • Focusing on the actual requirements, it minimizes the work for the Developer • During development? • Some tests may need to be reviewed due to development force a change in requirements • After completing the development? • It’s the only option, not the optimal one, if you have already written the code
  • 11. Introduction to tSQLt • The framework tSQLt was developed by Sebastian Meine and Dennis Lloyd, it is the open source framework for implementing unit tests in T-SQL for SQL Server • It works with all editions of SQL Server starting from SQL Server 2005 SP2 • It requires SQL CLR enabled
  • 12. Introduction to tSQLt • tSQLt is written in T-SQL • It doesn’t work on Azure SQL Database, nowadays • It works on Azure SQL Managed Instances ☺
  • 13. Benefits of using tSQLt • Unit tests will be written in T-SQL, you don’t need to learn new programming language • Data manipulation will be rolled back at the end of the test so you don’t need any data cleanup • Mock objects are supported • tSQLt can be integrated into SSDT projects or 3rd party tools
  • 14. Benefits of using tSQLt • Tests can be grouped within a single schema • You can use a setup routine for a group of tests or class • The output can be in plain text or XML
  • 15. tSQLt Setup: Install in your development DB • Download tSQLt scripts from tsqlt.org/downloads • Enable CLR at the SQL Server instance level • In each development database you want to install tSQLt • Enable TRUSTWORTHY property • Execute tSQLt.class.sql
  • 17. The anatomy of a unit test • Arrange (or Assemble) • Preparation of data on which the test will run • Isolation of the code from any external dependencies • Act • The system under test (SUT) will be executed and the output has been acquired as a result • Assert • The expected result will be compared with the obtained one, the test will fail or will have a positive outcome according to this comparison
  • 18. How does a test run with tSQLt • When we run a test through tSQLt, the framework traces the running test and starts a dedicated transaction • The configuration procedure for the test class will be executed (if existing) and afterward the test will be executed • At the end of the test, the tSQLt framework will rollback the dedicated transaction • The results will be stored in the tSQLt.TestResult table
  • 19. Our first unit test is for a Trigger ☺ • You developed a Trigger for AdventureWorks2017 to prevent the insertion of new products with values less than 10 as a “safety stock” • The Company Adventure Works LTD wishes to always have a warehouse stock of no less than 10 units for each product • To make our trigger simple, it will only respond to the OnInsert event, for INSERT commands
  • 20. Our first unit test is for a Trigger CREATE TRIGGER Production.TR_Product_SafetyStockLevel ON Production.Product AFTER INSERT AS BEGIN /* Avoid to insert products with safety stock level lower than 10! */ DECLARE @SafetyStockLevel SMALLINT; SELECT @SafetyStockLevel = SafetyStockLevel FROM inserted; IF (@SafetyStockLevel < 10) BEGIN -- Error!! EXEC Production.usp_Raiserror_SafetyStockLevel @Message = 'Safety stock level cannot be lower than 10!'; END; END;
  • 21. Possible test • Try to insert one correct row • Try to insert one wrong row and observe the error caught by the Trigger • Try to insert multiple rows in a single statements • Wrong and correct rows • Does the order matter? • Let’s start!! ☺
  • 22. Demo Let’s write our first unit test!
  • 23. Isolate dependencies • Tests often depend on data or the result of a stored procedure or function • This affects our test’s repeatability • We can’t rely on data being unchanged • We need to isolate • Data • Table constraints • Stored procedures • Functions
  • 24. Isolate stored procedures tSQLt.SpyProcedure [@ProcedureName = ] 'procedure name' [, [@CommandToExecute = ] 'command' ] • It replaces the execution of the stored procedure with the specified command • A log table named @ProcedureName_SpyProcedureLog is created and a new log entry is made for each fake execution of the “spied” procedure • https://bit.ly/2XWVZBl
  • 25. Summary • We discussed about the importance of unit testing applied to database development • We learn how to use tSQLt framework • We learned how to write our first unit test using tSQLt Think about triggers, SP and complex functions you wrote (those with more than 200 lines of code just to be clear ☺) would you feel safe in modifying them? If the answer is “No” the first thing to do is to write the unit tests, now you know how!
  • 26. Resources • Articles • What it is and why it is important for T-SQL code • https://bit.ly/3tfUTP8 • The tSQLt framework and the execution of a test • https://bit.ly/3oFy1Fb • How to write your first unit test for T-SQL code • https://bit.ly/3qkBRFq • tSQLt - https://tsqlt.org
  • 27. Resources • Videos • Implementare unit testing su Sql Server - Alessandro Alpi • https://www.youtube.com/watch?v=7tIHg3P0ea0 • Continuous Deployment, portare SQL Server nel mondo DevOps - Alessandro Alpi • https://www.youtube.com/watch?v=1jBm4MFFlPg • Tools • Red-Gate SQL Test • https://www.red-gate.com/products/sql-development/sql-test/ • TSQLUnit • https://github.com/aevdokimenko/tsqlunit
  • 29. #datasatpn February 27th, 2021 Data Saturday #1 Thanks! #datasatpn @segovoni Slide and demo: https://bit.ly/37Sa4oG