r/SQL • u/umairshariff23 • Jun 01 '26
Snowflake SQL unit tests implementation
Hey all!
I have reached a point where I am spending more time qa-ing my code than writing code and was looking at a way to make it more efficient and came across unit testing in software development.
My sql scripts sit at about 1.5k to 2k lines of code but the core of the script is usually 15-20 case when statements that contain the business logic. I wanted to ask the community if it is possible to build something that contains source data and expected outputs and compare the output of the script against those expected outputs for these test scenarios.
If so, how do you execute it? Do you keep the test data in the same script, do you create SPs for testing, how do you make the distinction between real data and test data? Are there any pitfalls I should be aware of? Are there any tools that will make this easier for me?
2
u/jshine13371 Jun 01 '26
Don't fully follow the exact granular ask, but the high level gist I'm getting is you probably need some form of refactoring. That'll make testing the core logic much simpler and flexible.
7
u/trippingcherry Jun 01 '26
It's not exactly unit tests but there is testing available in tools like DBT and dataform. My team operates out of bigquery so we use data form because it's native to the gcp platform. It lets us declare assertion statements, things expect to be true of the output. Something to look into if you're not familiar; a lot of other benefits as well such as using version control, automation of documentation, orchestration functionality etc.
6
u/lolcrunchy Jun 01 '26
If you're using TSQL, google "tsqlt"
2
u/Ginger-Dumpling Jun 01 '26
Not a Snowflake user and maybe misreading. If you're essentially trying to test a bunch of case statements independent of underlying queries, could you implement them as user defined functions? Then you can just have a test harness that only checks as many scenarios as you need to evaluate results for all cases?
2
u/JEDZBUDYN Jun 02 '26
1
u/No-Many-3856 Jul 18 '26
Exactly what I've been working on for months. Yes it's possible, you need to create fake data for your source tables for each test (a few lines to test a business case) then create the expected output to validate this business case. You can use dbt (v1.8+), it has a feature to run those unit tests but it runs on your dwh. I built an open source tool that generates the fake data and runs the unit tests locally, you can use it: "pip install mocksql"