@@ -2,22 +2,49 @@ const test = require('node:test');
2
2
const assert = require ( 'assert' ) ;
3
3
const { MyClass, Student } = require ( './main' ) ;
4
4
5
- test ( "Test MyClass's addStudent" , ( ) => {
6
- // TODO
7
- throw new Error ( "Test not implemented" ) ;
5
+ // 測試 MyClass 的 addStudent 方法
6
+ test ( "Test MyClass's addStudent" , async ( t ) => {
7
+ const myClass = new MyClass ( ) ;
8
+ const student = new Student ( ) ;
9
+ student . setName ( "John Doe" ) ;
10
+
11
+ const addedStudentId = myClass . addStudent ( student ) ;
12
+ assert . strictEqual ( addedStudentId , 0 , "應該將學生加入並返回正確的索引" ) ;
13
+
14
+ const nonStudent = { } ; // 模擬非 Student 實例
15
+ const nonStudentId = myClass . addStudent ( nonStudent ) ;
16
+ assert . strictEqual ( nonStudentId , - 1 , "非 Student 實例不應該被添加" ) ;
8
17
} ) ;
9
18
10
- test ( "Test MyClass's getStudentById" , ( ) => {
11
- // TODO
12
- throw new Error ( "Test not implemented" ) ;
19
+ // 測試 MyClass 的 getStudentById 方法
20
+ test ( "Test MyClass's getStudentById" , async ( t ) => {
21
+ const myClass = new MyClass ( ) ;
22
+ const student = new Student ( ) ;
23
+ student . setName ( "Jane Doe" ) ;
24
+ myClass . addStudent ( student ) ;
25
+
26
+ const retrievedStudent = myClass . getStudentById ( 0 ) ;
27
+ assert . strictEqual ( retrievedStudent . getName ( ) , "Jane Doe" , "應該返回正確的學生名稱" ) ;
28
+
29
+ const invalidStudent = myClass . getStudentById ( - 1 ) ;
30
+ assert . strictEqual ( invalidStudent , null , "無效索引應該返回 null" ) ;
13
31
} ) ;
14
32
15
- test ( "Test Student's setName" , ( ) => {
16
- // TODO
17
- throw new Error ( "Test not implemented" ) ;
33
+ // 測試 Student 的 setName 方法
34
+ test ( "Test Student's setName" , async ( t ) => {
35
+ const student = new Student ( ) ;
36
+ student . setName ( "John Smith" ) ;
37
+ assert . strictEqual ( student . name , "John Smith" , "setName 應該正確設置學生名稱" ) ;
38
+
39
+ student . setName ( 123 ) ; // 嘗試用非字符串設置名稱
40
+ assert . notStrictEqual ( student . name , 123 , "setName 應該忽略非字符串值" ) ;
18
41
} ) ;
19
42
20
- test ( "Test Student's getName" , ( ) => {
21
- // TODO
22
- throw new Error ( "Test not implemented" ) ;
23
- } ) ;
43
+ // 測試 Student 的 getName 方法
44
+ test ( "Test Student's getName" , async ( t ) => {
45
+ const student = new Student ( ) ;
46
+ assert . strictEqual ( student . getName ( ) , '' , "未設置名稱時應返回空字符串" ) ;
47
+
48
+ student . setName ( "Doe Jane" ) ;
49
+ assert . strictEqual ( student . getName ( ) , "Doe Jane" , "getName 應返回設置的學生名稱" ) ;
50
+ } ) ;
0 commit comments