douyu1656 2017-06-23 18:53
浏览 43
已采纳

如何编写单元测试以检查方法是否是线程安全的

I have an object like this:

type Store struct {
    mutex sync.RWMutex
    data  map[string]int
}

func (s * Store) Read(key string) int, error {
    // ...
    defer s.mutex.RUnlock()
    s.mutex.RLock()
    // ...
    return val, nil
}

func (s * Store) Write(key string, value int) error {
    // ...
    defer s.mutex.Unlock()
    s.mutex.Lock()
    // ...
    return nil
}

How should unit-tests to look like for methods Read & Write to check that they are thread safe?

I think there are already exists patterns for cases like this, but I didn't find anything.

I read about -race flag:

the race detector can detect race conditions only when they are actually triggered by running code, which means it's important to run race-enabled binaries under realistic workloads

My question is how to write unit-test which emulates realistic workloads.

  • 写回答

1条回答 默认 最新

  • douba3378 2017-06-23 18:55
    关注

    Run your tests with the Race detector. In short, run:

    go test -race
    

    Or to build a normal binary, such as to run on a staging server, use:

    go build -race
    

    But there are many more options, so best to read up on it :)

    If your goal is to test under realistic load, your best option is to compile your code with go build -race, then run it under realistic load. This probably means on a staging server. But don't confuse this with unit testing!

    Unit testing is for testing units--small parts of code, usually individual functions. Load/race testing is a different beast, and requires different tools and an entirely different approach.

    The fact that Go will easily run unit tests with the race detector is nice, and often catches races. But it will not, nor should not be expected to, catch all races, since the nature of unit test execution is entirely different from that of production execution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条