1
0
Fork 0
pr3-sose2026-fork/go/04-design-pattern/patterns/observer_test.go

70 lines
2.0 KiB
Go

package patterns_test
import (
"testing"
"gitty.informatik.th-mannheim.de/steger/pr3-sose2026/go/04-design-pattern/patterns"
)
// MockObserver is a test implementation of the Observer interface, used to verify that the Notify method correctly calls the Update method on registered observers
type MockObserver struct {
callCount int
}
// Update increments the callCount to track how many times the Update method has been called on this observer
func (mo *MockObserver) Update() {
mo.callCount++
}
// Table driven tests for the Subject's Notify method, covering various scenarios of registered and unregistered observers
func TestSubject_Notify(t *testing.T) {
type observer struct {
MockObserver
toRegister bool
expectedCallcount int
}
tests := []struct {
name string
observers []*observer
}{
{"No observers", []*observer{}},
{"Single unregistered observer", []*observer{&observer{MockObserver{0}, false, 0}}},
{"Single registered observer", []*observer{&observer{MockObserver{0}, true, 1}}},
{"Two registered observers", []*observer{&observer{MockObserver{0}, true, 1}, &observer{MockObserver{0}, true, 1}}},
{"One registered and one unregistered observers", []*observer{&observer{MockObserver{0}, true, 1}, &observer{MockObserver{0}, false, 0}}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := patterns.NewSubject()
for _, o := range tt.observers {
if o.toRegister {
s.Register(o)
}
}
s.Notify()
for _, o := range tt.observers {
if o.callCount != o.expectedCallcount {
t.Errorf("%s: expected a callcount of %v, actual: %v", tt.name, o.expectedCallcount, o.callCount)
}
//reset callcount & unregister
o.callCount = 0
s.Unregister(o)
}
//call notify when all observers are unregistered
s.Notify()
//expect a callcount of 0
for _, o := range tt.observers {
if o.callCount != 0 {
t.Errorf("%s: expected a callcount of 0, actual: %v", tt.name, o.callCount)
}
}
})
}
}