-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_bus_test.go
108 lines (86 loc) · 2 KB
/
command_bus_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
104
105
106
107
108
package commandbus
import (
"bytes"
"testing"
)
type TestCommand struct{}
type TestCommand2 struct{}
func TestNew(t *testing.T) {
bus := New()
if bus == nil {
t.Log("New command bus not created!")
t.Fail()
}
}
func TestCanGetRegisteredHandlerFunc(t *testing.T) {
bus := New()
test := 0
handler1 := func(cmd interface{}) { test = 1 }
handler2 := func(cmd interface{}) { test = 2 }
bus.RegisterHandler(&TestCommand{}, handler1)
bus.RegisterHandler(&TestCommand2{}, handler2)
bus.GetHandler(&TestCommand2{})(nil)
if test != 2 {
t.Log("Wrong handler called!")
t.Fail()
}
bus.GetHandler(&TestCommand{})(nil)
if test != 1 {
t.Log("Wrong handler called!")
t.Fail()
}
}
func TestCanUseHandler(t *testing.T) {
var buffer bytes.Buffer
bus := New()
command := &TestCommand{}
bus.RegisterHandler(command, func(cmd interface{}) {
buffer.WriteString("executed")
})
bus.Handle(command)
if buffer.String() != "executed" {
t.Log("Command was not executed!")
t.Fail()
}
}
func TestCanUseMiddleware(t *testing.T) {
var buffer bytes.Buffer
bus := New()
command := &TestCommand{}
bus.RegisterHandler(command, func(cmd interface{}) {
buffer.WriteString("executed")
})
bus.AddMiddleware(0, func(cmd interface{}, next HandlerFunc) {
buffer.WriteString("0")
next(cmd)
buffer.WriteString("0")
})
bus.Handle(command)
if buffer.String() != "0executed0" {
t.Log("Command was not executed!")
t.Fail()
}
}
func TestCanUsePrioritizedMiddleware(t *testing.T) {
var buffer bytes.Buffer
bus := New()
command := &TestCommand{}
bus.RegisterHandler(command, func(cmd interface{}) {
buffer.WriteString("a")
})
bus.AddMiddleware(0, func(cmd interface{}, next HandlerFunc) {
buffer.WriteString("0")
next(cmd)
buffer.WriteString("0")
})
bus.AddMiddleware(1, func(cmd interface{}, next HandlerFunc) {
buffer.WriteString("1")
next(cmd)
buffer.WriteString("1")
})
bus.Handle(command)
if buffer.String() != "10a01" {
t.Log("Execution occurred out of order!")
t.Fail()
}
}