0
0
Testing Fundamentalstesting~10 mins

Why database testing ensures data integrity in Testing Fundamentals - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test checks that data saved in the database matches what was input through the application. It verifies that no data is lost or changed incorrectly, ensuring data integrity.

Test Code - unittest
Testing Fundamentals
import sqlite3
import unittest

class TestDatabaseIntegrity(unittest.TestCase):
    def setUp(self):
        self.conn = sqlite3.connect(':memory:')
        self.cursor = self.conn.cursor()
        self.cursor.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

    def test_insert_and_retrieve(self):
        # Insert data
        self.cursor.execute('INSERT INTO users (name, age) VALUES (?, ?)', ('Alice', 30))
        self.conn.commit()

        # Retrieve data
        self.cursor.execute('SELECT name, age FROM users WHERE name = ?', ('Alice',))
        row = self.cursor.fetchone()

        # Assert data integrity
        self.assertIsNotNone(row)
        self.assertEqual(row[0], 'Alice')
        self.assertEqual(row[1], 30)

    def tearDown(self):
        self.conn.close()

if __name__ == '__main__':
    unittest.main()
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test starts and in-memory database is created with users tableEmpty database with users table ready-PASS
2Insert user data ('Alice', 30) into users tableDatabase contains one user record with name 'Alice' and age 30-PASS
3Retrieve user data where name is 'Alice'Query returns one record with name 'Alice' and age 30Check that retrieved data is not NonePASS
4Assert retrieved name equals 'Alice'Retrieved data name field is 'Alice'AssertEqual(row[0], 'Alice')PASS
5Assert retrieved age equals 30Retrieved data age field is 30AssertEqual(row[1], 30)PASS
6Test ends and database connection is closedDatabase connection closed-PASS
Failure Scenario
Failing Condition: Data inserted does not match data retrieved (e.g., wrong age or missing record)
Execution Trace Quiz - 3 Questions
Test your understanding
What does the test verify about the data in the database?
AThat the database connection is slow
BThat the database schema is empty
CThat the data retrieved matches the data inserted
DThat the application UI is responsive
Key Result
Always verify that data saved in the database can be retrieved exactly as expected to ensure data integrity.