以下代码的单元测试失败:
这是我的主要代码:
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 = / Users / 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工具test2json -t / private / var / folders / r0 / f7kkkm9526lgfz6jtgtphyww0000gn / T / ___ TestGetCountryRestClientError_in_api_provider_locprovider -test.v -test.run ^ TestGetCountrysetupupError 提供但未定义的标志:-test.v / private / var / folders / r0 / f7kkkm9526lgfz6jtgtphyww0000gn / T / ___ TestGetCountryRestClientError_in_api_provider_locprovider的用法: -嘲笑 使用'mock'标志告诉软件包其余部分您想使用模型。 流程结束,退出代码为1
答案 0 :(得分:4)
这似乎与golang/go issue 33869类似,后者依次指向go/issue 31859 "testing: panic in Init if flag.Parse has already been called "和此Go 1.13 instruction
现在在新的
Init
函数中注册了测试标志,该函数由生成的用于测试的主函数调用。
结果,现在仅在运行测试二进制文件时注册测试标志,,并且在程序包初始化期间调用flag.Parse
的程序包可能会导致测试失败。
如Sachin Raut中的the comments所述:
问题似乎出在外部库(
一起使用时效果很好github.com/mercadolibre/golang-restclient/rest
)上。
截至目前(2020年7月),该“golang-restclient/rest
”库不支持Go的最新版本。
与GO VERSIONS <= 1.12