-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock.go
More file actions
55 lines (46 loc) · 1.38 KB
/
Copy pathmock.go
File metadata and controls
55 lines (46 loc) · 1.38 KB
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
package funcmock
import (
"reflect"
)
func Mock(targetFnPtr interface{}) (controller *MockController) {
targetFn := reflect.ValueOf(targetFnPtr).Elem()
controller = &MockController{
counter: make(chan int),
callStack: make(chan map[int]*call),
}
go func() { controller.callStack <- make(map[int]*call) }()
go func() {controller.counter <- 0 }()
controller.targetFunc = targetFn
targetFnType := targetFn.Type()
numberOfOuts := targetFnType.NumOut()
controller.originalFunc = reflect.ValueOf(targetFn.Interface())
for i := 0; i < numberOfOuts; i++ {
controller.defaultYield = append(controller.defaultYield,
reflect.Zero(targetFnType.Out(i)))
}
mockFn := reflect.MakeFunc(targetFnType,
func(inValueSlice []reflect.Value) (yield []reflect.Value) {
callCount := controller.incrementCounter()
theCall := controller.NthCall(callCount - 1)
var param []interface{}
for i := 0; i < targetFnType.NumIn(); i++ {
param = append(param, inValueSlice[i].Interface())
}
theCall.updateParam(param)
if numberOfOuts == len(theCall.yield) {
// if user has set the return values the spit them out
for i := 0; i < numberOfOuts; i++ {
yield = append(yield,
sanitizeReturn(
targetFnType.Out(i),
theCall.yield[i]))
}
} else {
yield = controller.defaultYield
}
return yield
},
)
targetFn.Set(mockFn)
return controller
}