stonecqrs/dispatcher_test.go
Rene Nochebuena 3d2e5ec027
Some checks failed
Go CI/CD / go-ci (push) Has been cancelled
Add Dispatcher implementation for CQRS pattern
Introduced a Dispatcher to manage command, query, and event handlers in a thread-safe manner utilizing read-write mutexes. This includes handler registration and dispatching logic, error handling for unregistered handlers, and support for concurrent operations. Added comprehensive tests for handler registration, dispatching, and error scenarios.
2025-04-13 00:59:18 -06:00

113 lines
2.2 KiB
Go

package stonecqrs
import (
"context"
"fmt"
"testing"
)
type testCommand struct {
message string
}
type testQuery struct {
message string
}
type testEvent struct {
message string
}
type unknownEvent struct{}
type testCommandHandler struct{}
func (handler *testCommandHandler) Handle(
ctx context.Context, cmd Command,
) ([]Event, error) {
fmt.Println(cmd)
return []Event{
testEvent{message: "test"},
}, nil
}
type testQueryHandler struct{}
func (handler *testQueryHandler) Handle(
ctx context.Context, query Query,
) (interface{}, error) {
fmt.Println(query)
return "test", nil
}
type testEventHandler struct{}
func (handler *testEventHandler) Handle(
ctx context.Context, event Event,
) error {
fmt.Println(event)
return nil
}
func Test_NewDispatcher(t *testing.T) {
d := NewDispatcher()
if d == nil {
t.Fatal("expected non-nil dispatcher")
}
}
func Test_Register(t *testing.T) {
d := NewDispatcher()
d.RegisterCommandHandler(testCommand{}, &testCommandHandler{})
d.RegisterQueryHandler(testQuery{}, &testQueryHandler{})
d.RegisterEventHandler(testEvent{}, &testEventHandler{})
}
func Test_DispatchCommandWithEvents(t *testing.T) {
d := NewDispatcher()
d.RegisterCommandHandler(testCommand{}, &testCommandHandler{})
d.RegisterQueryHandler(testQuery{}, &testQueryHandler{})
d.RegisterEventHandler(testEvent{}, &testEventHandler{})
_, err := d.DispatchCommand(context.Background(), testCommand{})
if err != nil {
t.Fatal(err)
}
}
func Test_DispatchQuery(t *testing.T) {
d := NewDispatcher()
d.RegisterQueryHandler(testQuery{}, &testQueryHandler{})
_, err := d.DispatchQuery(context.Background(), testQuery{})
if err != nil {
t.Fatal(err)
}
}
func Test_UnknownEvent(t *testing.T) {
d := NewDispatcher()
d.RegisterCommandHandler(testCommand{}, &testCommandHandler{})
d.RegisterQueryHandler(testQuery{}, &testQueryHandler{})
d.RegisterEventHandler(testEvent{}, &testEventHandler{})
_, err := d.DispatchCommand(context.Background(), unknownEvent{})
if err == nil {
t.Fatal("expected error")
}
err = d.DispatchEvent(context.Background(), unknownEvent{})
if err == nil {
t.Fatal("expected error")
}
err = d.DispatchEvent(context.Background(), unknownEvent{})
if err == nil {
t.Fatal("expected error")
}
}