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.