-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_test.go
103 lines (89 loc) · 2.34 KB
/
new_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package factory
import (
"errors"
"testing"
)
func init() {
Singleton[testRepo]()
}
type testRepo struct {
}
func (tp *testRepo) Hello() {
panic(errors.New("test repo hello called"))
}
type testStruct struct{}
func (ts *testStruct) TestStruct() {
panic(errors.New("constructor called"))
}
func (ts *testStruct) Init() {
panic(errors.New("init called"))
}
func (ts *testStruct) InitWithReturn() error {
return nil
}
func (ts testStruct) MyInit(tp *testRepo) {
if tp != nil {
tp.Hello()
}
}
func (ts *testStruct) MyErrorInit(tp testRepo) {
tp.Hello()
}
func (ts *testStruct) nonExistentMethodName() {
}
func TestNewWithOption(t *testing.T) {
test_cases := []struct {
name string
option *Option
expectedPanic error
expectError bool
}{
{
name: "OptionWithInitMethod",
option: NewOption().UseConstructor(true),
expectedPanic: errors.New("constructor called"),
expectError: true,
},
{
name: "OptionWithNonexistentMethod",
option: NewOption().InitMethodName("NonExistentMethodName"),
expectedPanic: errors.New(""),
expectError: false,
},
{
name: "OptionWithInitWithReturn",
option: &Option{useConstructor: false, initMethodName: "InitWithReturn"},
expectedPanic: errors.New("init method 'InitWithReturn' must not have return values"),
expectError: true,
},
{
name: "OptionWithMyInitMethodWithWareObjParams",
option: &Option{useConstructor: false, initMethodName: "MyInit"},
expectedPanic: errors.New("test repo hello called"),
expectError: true,
},
{
name: "OptionWithMyInitMethodWithWareObjErrorParams",
option: &Option{useConstructor: false, initMethodName: "MyErrorInit"},
expectedPanic: errors.New("create testStruct error: method MyErrorInit's 1 argument must be a struct point or an interface"),
expectError: true,
},
}
for _, tt := range test_cases {
t.Run(tt.name, func(t *testing.T) {
defer func() {
r := recover()
if (r != nil) != tt.expectError {
t.Errorf("panic = %v, expectError %v", r, tt.expectError)
return
}
if tt.expectError && r != nil {
if r.(error).Error() != tt.expectedPanic.Error() {
t.Errorf("Got panic = %v, want %v", r, tt.expectedPanic)
}
}
}()
NewWithOption[testStruct](tt.option)
})
}
}