Answer the question
In order to leave comments, you need to log in
How to write a test to protect against race condition?
Let's say I have some library
package v1
var balance int
//Deposit ...
func Deposit(amount int) {
balance = balance + amount
}
//Balance ...
func Balance() int {
return balance
}
func setBalance(amount int) {
balance = amount
}
func TestRaceDeposit(t *testing.T) {
setBalance(0)
ch := make(chan struct{})
go func() {
Deposit(10)
ch <- struct{}{}
}()
Deposit(10)
<-ch
if Balance() != 20 {
t.Errorf("unexpected balance: value - %d expect 20", Balance())
}
}
Answer the question
In order to leave comments, you need to log in
I would write like this
func TestRaceDeposit(t *testing.T) {
setBalance(0)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
Deposit(10)
wg.Done()
}()
}
wg.Wait()
expect := 100
got := Balance()
if got != expect {
t.Errorf("unexpected balance: value - %d expect %d", got, expect)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question