【发布时间】:2020-07-28 22:58:34
【问题描述】:
以下代码的单元测试失败:
这是我的主要代码:
package locprovider
import (
"encoding/json"
"fmt"
"net/http"
"api/domain/location"
"api/utils/error"
"github.com/mercadolibre/golang-restclient/rest"
)
const (
getCountryUrl = "https://api.mercadolibre.com/countries/%s"
)
func GetCountry(countryId string) (*location.Country, *error.ApiError) {
response := rest.Get(fmt.Sprintf(getCountryUrl, countryId))
if response == nil || response.Response == nil {
return nil, &error.ApiError {
Status: http.StatusInternalServerError,
Message: fmt.Sprintf("invalid restclient response when trying to get country %s", countryId),
}
}
if response.StatusCode > 299 {
var apiError error.ApiError
if err := json.Unmarshal(response.Bytes(), &apiError); err != nil {
return nil, &error.ApiError {
Status: http.StatusInternalServerError,
Message: fmt.Sprintf("invalid error response when getting country %s", countryId),
}
}
return nil, &apiError
}
var result location.Country
if err := json.Unmarshal(response.Bytes(), &result); err != nil {
return nil, &error.ApiError {
Status: http.StatusInternalServerError,
Message: fmt.Sprintf("error when trying to unmarshal country data for %s", countryId),
}
}
return &result, nil
}
这是我的单元测试代码:
package locprovider
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestGetCountryRestClientError(t *testing.T) {
// Execution:
country, err := GetCountry("AR")
// Validation:
assert.Nil(t, country)
assert.NotNil(t, err)
assert.EqualValues(t, 500, err.Status)
assert.EqualValues(t, "invalid restclient response when trying to get country AR", err.Message)
}
当我执行这个单元测试时,我遇到了以下错误,我不确定它为什么会发生。
我几乎没有来自其他 go 包的其他单元测试,它们工作正常,没有这个错误。
GOROOT=/usr/local/Cellar/go/1.13.3/libexec #gosetup GOPATH=/用户/abc/go-testing #gosetup /usr/local/Cellar/go/1.13.3/libexec/bin/go test -c -o /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider api/provider/locprovider #gosetup /usr/local/Cellar/go/1.13.3/libexec/bin/go tool test2json -t /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider -test.v -test.run ^TestGetCountryRestClientError$ #gosetup 提供但未定义的标志:-test.v /private/var/folders/r0/f7kkkm9526lgfz6jtgtphyww0000gn/T/___TestGetCountryRestClientError_in_api_provider_locprovider的用法: -嘲笑 使用 'mock' 标志告诉 package rest 你想使用模型。 进程以退出代码 1 结束
【问题讨论】:
-
你试过运行
go test -mock吗? -
使用 -mock 选项仍然会出现同样的错误。
标签: unit-testing go goland