在golang中重新定义const以进行测试

时间:2015-11-18 07:51:23

标签: unit-testing testing go

我正在为服务编写http客户端并进行测试我想使用net/http/httptest服务器而不是调用远程API。如果我将baseUrl设置为我的测试服务器的url的全局变量,我可以轻松地执行此操作。但是,这会使生产代码更加脆弱,因为baseUrl也可以在运行时更改。我的偏好是为生产代码baseUrl const但仍然可以更改。

package main
const baseUrl = "http://google.com"

// in main_test.go
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  ...
 }
const baseUrl = ts.URL
// above line throws const baseUrl already defined error

1 个答案:

答案 0 :(得分:6)

如果您的代码使用const值,则它不是测试友好型(关于使用该参数的不同值进行测试)。

您可以通过轻微的重构来解决您的问题。假设你有一个使用这个const的函数:

const baseUrl = "http://google.com"

func MyFunc() string {
    // use baseUrl
}

您可以创建另一个以基本网址作为参数的功能,原始MyFunc()会将其调用:

const baseUrl_ = "http://google.com"

func MyFunc() string {
    // Call other function passing the const value
    return myFuncImpl(baseUrl_)
}

func myFuncImpl(baseUrl string) string {
    // use baseUrl
    // Same implementation that was in your original MyFunc() function
}

这样,您的库的API不会更改,但现在您可以通过测试MyFunc()来测试原始myFuncImpl()的功能,并且您可以传递任何值以进行测试。

调用MyFunc()将保持安全,因为它始终将const baseUrl_传递给实现现在所在的myFuncImpl()。您决定是否导出这个新的myFuncImpl()函数;它可能仍然未被报告,因为测试代码可能(应该)放在同一个包中,可以毫无问题地调用它。