@@ -2,22 +2,41 @@ 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" ) ;
8
- } ) ;
5
+ test ( "Test MyClass's addStudent" , async ( t ) => {
6
+ const myClass = new MyClass ( ) ;
7
+ const student = new Student ( ) ;
8
+ student . setName ( "John Doe" ) ;
9
+
10
+ // 測試添加學生是否成功
11
+ const index = myClass . addStudent ( student ) ;
12
+ assert . strictEqual ( index , 0 , "Should return the index of the added student" ) ;
9
13
10
- test ( "Test MyClass's getStudentById" , ( ) => {
11
- // TODO
12
- throw new Error ( "Test not implemented" ) ;
14
+ // 測試添加非Student實例
15
+ const nonStudent = { name : "Fake Student" } ;
16
+ const nonStudentIndex = myClass . addStudent ( nonStudent ) ;
17
+ assert . strictEqual ( nonStudentIndex , - 1 , "Should return -1 for non-Student instances" ) ;
13
18
} ) ;
14
19
15
- test ( "Test Student's setName" , ( ) => {
16
- // TODO
17
- throw new Error ( "Test not implemented" ) ;
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
+ // 測試通過有效ID獲取學生
27
+ const fetchedStudent = myClass . getStudentById ( 0 ) ;
28
+ assert . strictEqual ( fetchedStudent . getName ( ) , "Jane Doe" , "Should fetch the correct student by ID" ) ;
29
+
30
+ // 測試使用無效ID獲取學生
31
+ const invalidStudent = myClass . getStudentById ( - 1 ) ;
32
+ assert . strictEqual ( invalidStudent , null , "Should return null for invalid IDs" ) ;
18
33
} ) ;
19
34
20
- test ( "Test Student's getName" , ( ) => {
21
- // TODO
22
- throw new Error ( "Test not implemented" ) ;
23
- } ) ;
35
+ test ( "Test Student's setName and getName" , async ( t ) => {
36
+ const student = new Student ( ) ;
37
+ student . setName ( "John Smith" ) ;
38
+ assert . strictEqual ( student . getName ( ) , "John Smith" , "setName and getName should correctly set and return the student's name" ) ;
39
+
40
+ student . setName ( 12345 ) ; // 嘗試使用非字符串設置名字
41
+ assert . notStrictEqual ( student . getName ( ) , 12345 , "setName should not accept non-string values" ) ;
42
+ } ) ;
0 commit comments