Stored procedure testing in Testing Fundamentals - Build an Automation Script
import unittest import pyodbc class TestStoredProcedure(unittest.TestCase): def setUp(self): self.conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=TestDB;UID=user;PWD=password') self.cursor = self.conn.cursor() def tearDown(self): self.cursor.close() self.conn.close() def test_get_employee_by_id(self): employee_id = 101 expected_name = 'John Doe' expected_department = 'Sales' # Call stored procedure with parameter self.cursor.execute("EXEC GetEmployeeById ?", employee_id) row = self.cursor.fetchone() # Assert one record returned self.assertIsNotNone(row, 'No data returned from stored procedure') # Assert employee ID matches self.assertEqual(row.EmployeeID, employee_id, f'Expected EmployeeID {employee_id}') # Assert employee name matches self.assertEqual(row.Name, expected_name, f'Expected Name {expected_name}') # Assert employee department matches self.assertEqual(row.Department, expected_department, f'Expected Department {expected_department}') if __name__ == '__main__': unittest.main()
The setUp method opens a database connection and cursor before each test.
The tearDown method closes them after each test to avoid resource leaks.
The test test_get_employee_by_id calls the stored procedure using a parameterized query to prevent SQL injection.
It fetches one row and asserts it is not None, meaning data was returned.
Then it checks the employee ID, name, and department fields match expected values.
Using unittest assertions helps clearly report failures.
This structure ensures clean setup, execution, validation, and cleanup for reliable stored procedure testing.
Now add data-driven testing with 3 different employee IDs and expected results
Practice
Solution
Step 1: Understand stored procedure testing goal
Testing stored procedures means checking if they do what they are supposed to do.Step 2: Identify correct purpose
Creating tables, deleting data, or changing schema are not testing goals but database operations.Final Answer:
To verify that the procedure performs the expected operations correctly -> Option AQuick Check:
Testing = Verify expected operations [OK]
- Confusing testing with creating or deleting data
- Thinking testing changes database structure
- Assuming testing runs automatically without checks
GetUserData with an input parameter userId?Solution
Step 1: Recall correct syntax for calling stored procedures
The standard SQL command to run a stored procedure isCALL procedure_name(parameters);Step 2: Match syntax with options
Only CALL GetUserData(userId); usesCALLwith parentheses and parameter correctly.Final Answer:
CALL GetUserData(userId); -> Option DQuick Check:
CALL + procedure + (params) = correct call [OK]
- Using EXECUTE without parentheses
- Using RUN PROCEDURE which is invalid syntax
- Forgetting parentheses around parameters
CALL CalculateDiscount(100, 0.1);If the procedure returns the discounted price by subtracting the discount (price * rate), what is the expected output?
Solution
Step 1: Understand inputs and calculation
Price is 100, discount rate is 0.1 (10%). Discount amount = 100 * 0.1 = 10.Step 2: Calculate discounted price
Discounted price = 100 - 10 = 90.Final Answer:
90 -> Option CQuick Check:
100 - (100*0.1) = 90 [OK]
- Adding instead of subtracting discount
- Using discount rate as final price
- Confusing discount amount with discounted price
CALL UpdateUserEmail(123, 'newemail@example.com');But it returns an error:
ERROR: procedure UpdateUserEmail does not exist.What is the most likely cause?
Solution
Step 1: Analyze error message
The error says the procedure does not exist, which means the database cannot find a procedure namedUpdateUserEmail.Step 2: Identify likely cause
This usually happens if the procedure name is wrong or it was not created.Final Answer:
The procedure name is misspelled or does not exist -> Option AQuick Check:
Error about procedure existence = name or creation issue [OK]
- Assuming input data causes procedure not found error
- Blaming connection issues without checking procedure
- Ignoring error message details
CalculateTax that takes an income amount and returns tax owed.The procedure has a bug: it returns NULL for zero income instead of 0.
Which test case will best detect this bug?
Solution
Step 1: Understand the bug
The procedure returns NULL instead of 0 when income is zero.Step 2: Choose test case to detect bug
Testing with zero income and expecting 0 will reveal if NULL is returned incorrectly.Final Answer:
Call CalculateTax(0) and check if result is 0 -> Option BQuick Check:
Test zero input to catch NULL instead of 0 bug [OK]
- Testing only positive values misses zero case
- Testing negative income when not required
- Assuming NULL input tests zero income bug
Ready to prove it?
Pass the test and this pattern moves unknown
