在golang中重新定义const以进行测试 [英] Redefine const in golang for test

查看:52
本文介绍了在golang中重新定义const以进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing an http client for a service and for testing I want to use a net/http/httptest server instead of calling out to the remote API. I can easily do this if I make the baseUrl a global variable which gets set to the url of my test server. However, this makes the production code more fragile because baseUrl can also be changed during runtime. My preference would be to make baseUrl a const for production code but still be able to change.

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

推荐答案

如果您的代码使用const值,则它不是 testing-friendly (关于使用该参数的不同值进行测试).

If your code uses a const value, it is not testing-friendly (regarding testing with different values of that parameter).

您可以通过稍微的重构来解决您的问题.假设您有一个使用此const的函数:

You could approach your problem with a slight refactoring. Let's say you have a function that uses this const:

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

func MyFunc() string {
    // use baseUrl
}

您可以创建另一个将基本URL作为参数的函数,原始的 MyFunc()会调用此函数:

You could create another function that takes base URL as a parameter, and your original MyFunc() calls this:

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不会更改,但是现在您可以通过测试 myFuncImpl()来测试原始 MyFunc()的功能,然后可以传递任何值进行测试.

This way the API of your library doesn't change, but now you can test the functionality of your original MyFunc() by testing myFuncImpl(), and you can pass any value to test with.

调用 MyFunc()将始终保持安全,因为它始终将const baseUrl _ 传递给实现所在的 myFuncImpl().由您决定是否将此新的 myFuncImpl()函数导出;否则,请执行以下操作.它可能仍未导出,因为可能(应该)将测试代码放在同一程序包中,并且可以毫无问题地调用它.

Calling MyFunc() will remain safe as it always passes the const baseUrl_ to myFuncImpl() where the implementation now resides. It's your decision whether you make this new myFuncImpl() function exported or not; it may remain unexported as testing code may (should) be placed in the same package and can call it without problems.

这篇关于在golang中重新定义const以进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆