goweb/cqrs/middleware_test.go

65 lines
1.3 KiB
Go
Raw Permalink Normal View History

2020-04-16 16:32:02 +02:00
package cqrs
import (
"context"
"testing"
)
func TestBasicCommandMiddleware(t *testing.T) {
2020-11-16 19:12:13 +01:00
dispatcher := NewDispatcher()
2020-04-16 16:32:02 +02:00
handlerCalled := false
handleTestCommand := func(ctx context.Context, cmd Command) error {
handlerCalled = true
return nil
}
middlewareCalled := false
commandMiddleware := func(next CommandHandler) CommandHandler {
fn := func(ctx context.Context, cmd Command) error {
middlewareCalled = true
return next.Handle(ctx, cmd)
}
return CommandHandlerFunc(fn)
}
2020-11-16 19:12:13 +01:00
dispatcher.RegisterCommand(
2020-04-16 16:32:02 +02:00
MatchCommandRequest(&testCommandRequest{}),
CommandHandlerFunc(handleTestCommand),
commandMiddleware,
)
cmd := &testCommandRequest{
Foo: "bar",
}
ctx := context.Background()
2020-11-16 19:12:13 +01:00
result, err := dispatcher.Exec(ctx, cmd)
2020-04-16 16:32:02 +02:00
if err != nil {
t.Error(err)
}
if result == nil {
t.Error("result should not be nil")
}
if result.Command() == nil {
t.Error("result.Command() should not be nil")
}
if e, g := result.Command().Request(), cmd; e != g {
t.Errorf("result.Command().Request(): expected '%v', got '%v'", e, g)
}
if e, g := middlewareCalled, true; e != g {
t.Errorf("middlewareCalled: expected '%v', got '%v'", e, g)
}
if e, g := handlerCalled, true; e != g {
t.Errorf("handlerCalled: expected '%v', got '%v'", e, g)
}
}