github.com/hannamil/mapper@v0.1.1/mapper_test.go (about) 1 package mapper 2 3 import ( 4 "reflect" 5 "testing" 6 "time" 7 ) 8 type ( 9 Class struct { 10 Name string 11 Level string 12 } 13 14 Person struct { 15 Id string 16 Name string 17 Age int 18 Birth time.Time 19 Class Class 20 } 21 22 Student struct { 23 No int 24 Name string 25 Age int 26 Class interface{} 27 } 28 ) 29 30 func BenchmarkMapper(b *testing.B) { 31 tests := []struct { 32 source interface{} 33 dest interface{} 34 }{ 35 {source: nil, dest: nil}, 36 {source: Person{}, dest: nil}, 37 {source: Person{Id: "nih", Name: "chris han", Age: 30, Class: Class{Name: "Deep learning", Level: "basic"}}, dest: Student{}}, 38 {source: Person{Name: "chris han", Age: 30, Birth: time.Now().Add(time.Hour*24*365*30*-1)}, dest: Student{}}, 39 } 40 for _, tt := range tests { 41 _, _ = Mapper(tt.source, tt.dest) 42 } 43 } 44 45 func TestMapper(t *testing.T) { 46 type args struct { 47 source interface{} 48 dest interface{} 49 } 50 tests := []struct { 51 name string 52 args args 53 want interface{} 54 wantErr bool 55 }{ 56 {name: "Zero value source", args: args{ source: nil, dest: Student{}}, want: nil, wantErr: true}, 57 {name: "Zero value dest", args: args{ source: Person{}, dest: nil}, want: nil, wantErr: true}, 58 {name: "Zero value source/dest", args: args{ source: nil, dest: nil}, want: nil, wantErr: true}, 59 {name: "Default value source", args: args{ source: Person{}, dest: Student{}}, want: Student{Class: Class{}}, wantErr: false}, 60 {name: "Default value dest", args: args{ source: Person{Name: "chris han", Age: 30, Birth: time.Now().Add(time.Hour*24*365*30*-1)}, dest: Student{}}, want: Student{Name: "chris han", Age: 30, Class: Class{}}, wantErr: false}, 61 {name: "Normal", args: args{ source: Person{Id: "nih", Name: "chris han", Age: 30, Class: Class{Name: "Deep learning", Level: "basic"}}, dest: Student{}}, want: Student{Name: "chris han", Age: 30, Class: Class{Name: "Deep learning", Level: "basic"}}, wantErr: false}, 62 } 63 for _, tt := range tests { 64 t.Run(tt.name, func(t *testing.T) { 65 got, err := Mapper(tt.args.source, tt.args.dest) 66 if (err != nil) != tt.wantErr { 67 t.Errorf("Mapper() error = %v, wantErr %v", err, tt.wantErr) 68 return 69 } 70 if err == nil && !IsEqual(got, tt.want) { 71 t.Errorf("Mapper() got = %v, want = %v", got, tt.want) 72 } 73 }) 74 } 75 } 76 77 func IsEqual(dest, want interface{}) bool { 78 return reflect.DeepEqual(dest.(reflect.Value).Interface().(Student), want) 79 }