Last active
April 25, 2025 23:44
-
-
Save juanpabloaj/68775ead8c4a66367fe83bae0df12196 to your computer and use it in GitHub Desktop.
Testing of Goroutines with WaitGroup and time.After
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"testing" | |
"time" | |
) | |
type Actor interface { | |
Perform() | |
} | |
func Cinema(a Actor) { | |
go a.Perform() | |
} | |
type mockActor struct{ wg *sync.WaitGroup } | |
func (m mockActor) Perform() { | |
m.wg.Done() | |
} | |
func TestCinema(t *testing.T) { | |
var wg sync.WaitGroup | |
wg.Add(1) | |
Cinema(mockActor{wg: &wg}) | |
done := make(chan struct{}) | |
go func() { | |
defer close(done) | |
wg.Wait() | |
}() | |
select { | |
case <-done: | |
case <-time.After(500 * time.Millisecond): | |
t.Fatalf("timeout: Perform did not finish in 500 ms") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment