MySQL是一款常用的關系型數據庫管理系統,而測試用例則是測試數據庫性能和功能的重要手段。下面將介紹如何寫MySQL測試用例。
-- 第一步,準備測試數據 CREATE TABLE `student` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) NOT NULL, `age` int(11) NOT NULL, `score` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; INSERT INTO `student` (`name`, `age`, `score`) VALUES ('張三', 18, 90); INSERT INTO `student` (`name`, `age`, `score`) VALUES ('李四', 19, 85); INSERT INTO `student` (`name`, `age`, `score`) VALUES ('王五', 20, 88); -- 第二步,編寫測試用例 -- 定義測試用例模塊 CREATE PROCEDURE `test_get_student` () BEGIN DECLARE result INT; DECLARE expected INT; -- 測試用例1:查詢單個學生數據 SELECT score INTO result FROM student WHERE name = '張三'; SET expected = 90; IF result = expected THEN SELECT "Test case 1 passed."; ELSE SELECT "Test case 1 failed."; END IF; -- 測試用例2:查詢年齡在20歲以下的學生數量 SELECT COUNT(*) INTO result FROM student WHERE age< 20; SET expected = 2; IF result = expected THEN SELECT "Test case 2 passed."; ELSE SELECT "Test case 2 failed."; END IF; -- 測試用例3:更新學生數據 UPDATE student SET score = 95 WHERE name = '李四'; SELECT score INTO result FROM student WHERE name = '李四'; SET expected = 95; IF result = expected THEN SELECT "Test case 3 passed."; ELSE SELECT "Test case 3 failed."; END IF; -- 測試用例4:刪除學生數據 DELETE FROM student WHERE name = '王五'; SELECT COUNT(*) INTO result FROM student WHERE name = '王五'; SET expected = 0; IF result = expected THEN SELECT "Test case 4 passed."; ELSE SELECT "Test case 4 failed."; END IF; END; -- 第三步,運行測試用例 CALL test_get_student();
以上測試用例包括查詢、更新和刪除學生數據的測試,通過比較結果和期望值的方法驗證是否正確。在寫測試用例時,需要明確測試目標、輸入參數和預期結果,并對多種情況進行充分測試,保證數據庫的性能和功能。