D
D
di2019-10-01 11:10:05
go
di, 2019-10-01 11:10:05

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
}

A race condition is possible here if the function is called in different goroutines.
Does such a test case have the right to life?
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())
  }
}

To be able to catch a race condition when running tests with the -race flag

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladislav, 2019-10-01
@Delgus

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 question

Ask a Question

731 491 924 answers to any question