请为这段代码写一个单元测试: 获得某个时间点的价格 返回最接近指定时间点的交易价格 参数: t 指的是t毫秒之前最新的价格func c AggTradeCounter GetPricectx contextContext t int64 float64 int64 bool error sTime = atomicLoadInt64&clastTradeTime - t var e WsAggT
import ( "context" "testing" )
func TestAggTradeCounter_GetPrice(t *testing.T) { c := &AggTradeCounter{ lastTradeTime: 10000, data: []*WsAggTradeEvent{ {TradeTime: 9000, Price: "10.00"}, {TradeTime: 11000, Price: "11.00"}, {TradeTime: 12000, Price: "12.00"}, }, }
// 测试能够正确返回价格
p, tt, ok, err := c.GetPrice(context.Background(), 1000)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
if !ok {
t.Errorf("expected ok to be true, but got false")
}
if p != 10.0 {
t.Errorf("expected price to be 10.0, but got %v", p)
}
if tt != 9000 {
t.Errorf("expected trade time to be 9000, but got %v", tt)
}
// 测试找不到数据时能够返回错误
_, _, ok, err = c.GetPrice(context.Background(), 20000)
if err == nil {
t.Errorf("expected error, but got nil")
}
if ok {
t.Errorf("expected ok to be false, but got true")
}
// 测试价格格式错误时能够返回错误
c.data[0].Price = "invalid"
_, _, ok, err = c.GetPrice(context.Background(), 1000)
if err == nil {
t.Errorf("expected error, but got nil")
}
if ok {
t.Errorf("expected ok to be false, but got true")
}
}
原文地址: http://www.cveoy.top/t/topic/bCkA 著作权归作者所有。请勿转载和采集!