我目前正在研究为Go中的服务创建一些单元测试,以及在该功能之上构建的其他函数,我想知道什么是单元测试的最佳方式那在Go?我的代码如下所示:golang中的单元测试
type BBPeripheral struct {
client *http.Client
endpoint string
}
type BBQuery struct {
Name string `json:"name"`
}
type BBResponse struct {
Brand string `json:"brand"`
Model string `json:"model"`
...
}
type Peripheral struct {
Brand string
Model string
...
}
type Service interface {
Get(name string) (*Peripheral, error)
}
func NewBBPeripheral(config *peripheralConfig) (*BBPeripheral, error) {
transport, err := setTransport(config)
if err != nil {
return nil, err
}
BB := &BBPeripheral{
client: &http.Client{Transport: transport},
endpoint: config.Endpoint[0],
}
return BB, nil
}
func (this *BBPeripheral) Get(name string) (*Peripheral, error) {
data, err := json.Marshal(BBQuery{Name: name})
if err != nil {
return nil, fmt.Errorf("BBPeripheral.Get Marshal: %s", err)
}
resp, err := this.client.Post(this.endpoint, "application/json", bytes.NewBuffer(data))
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf(resp.StatusCode)
}
var BBResponse BBResponse
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(body, &BBResponse)
if err != nil {
return nil, err
}
peripheral := &Peripheral{}
peripheral.Model = BBResponse.Model
if peripheral.Model == "" {
peripheral.Model = NA
}
peripheral.Brand = BBResponse.Brand
if peripheral.Brand == "" {
peripheral.Brand = NA
}
return peripheral, nil
}
测试该代码,并使用这些功能来旋转了一个单独的goroutine要像服务器上,使用http.httptest包,还是其他什么东西的代码的最有效的方法是什么?这是我第一次尝试编写测试,然后我不知道如何。
Go有自己内置的测试工具。看到这里https://golang.org/pkg/testing/ ...如果你在github上玩游戏以查看其他使用得当的软件包,你会经常遇到以_test.go结尾的文件..这些文件是进行单元测试,但使用cmd go测试并使用测试包。你提到的软件包也是一个很好的开始。在测试之后,因为这是一个服务器,我可能会跟进一个Siege测试来给服务器增加一些压力,看看它是如何处理的https://www.joedog.org/siege-home/ – reticentroot