我有一个这样的对象:
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
}
Read
和 Write
方法的单元测试应该如何检查它们是否线程安全?
我认为这种情况已经存在模式,但我没有找到任何东西。
我读到关于 -race
标志的内容:
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
我的问题是如何编写模拟实际工作负载的单元测试。
最佳答案
使用 Race detector 运行测试.简而言之,运行:
go test -race
或者构建一个普通的二进制文件,比如在临时服务器上运行,使用:
go build -race
但是还有更多选择,所以最好仔细阅读 :)
如果您的目标是在实际负载下进行测试,最好的选择是使用 go build -race
编译您的代码,然后在实际负载下运行它。这可能意味着在登台服务器上。但是不要将它与单元测试混淆!
单元测试用于测试单元——一小部分代码,通常是单个函数。负载/竞争测试是另一种野兽,需要不同的工具和完全不同的方法。
Go 可以使用竞争检测器轻松运行单元测试这一事实很好,而且经常会出现竞争。但它不会,也不应期望 catch 所有的竞争,因为单元测试执行的性质与生产执行的性质完全不同。
关于multithreading - 如何编写单元测试来检查方法是否线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44728201/