unit-testing - 在 Go 中为 httptest.NewServer 使用自定义 URL

标签 unit-testing http go

我通过在 Go 语言中创建一个 http 测试服务器来在一些 rest 调用上运行 UT。我的代码如下。

type student struct{
FirstName string
LastName string
}

func testGetStudentName() {
    testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    response = new(student)
    response.FirstName = "Some"
    response.LastName = "Name"
    b, err := json.Marshal(response)
    if err == nil {
            fmt.Fprintln(w, string(b[:]))
        }
    }))
    defer ts.Close()
    student1 := base.getStudent("123")
    log.Print("testServerUrl",testServer.URL) //prints out http://127.0.0.1:49931 ( port changes every time this is run)

   ts.URL = "http://127.0.0.1:8099" //this assignment does not quite change the URL of the created test server.
}

在被测试的文件中,

var baseURL = "http://originalUrl.com"
var mockUrl = "http://127.0.0.1:49855"
func Init(mockServer bool){
    if mockServer {
        baseURL = mockUrl
    }
}

func getStudent(id String){
     url := baseUrl + "/student/" + id
     req, err := http.NewRequest("GET", url, nil)
}

这个 init 是从我的测试中调用的。

这会创建一个新的测试服务器并在随机端口上运行调用。我可以在我指定的端口上运行此服务器吗?

最佳答案

大多数应用程序使用在 NewServer 或 NewUnstartedServer 中分配的端口,因为该端口不会与机器上正在使用的端口冲突。他们没有分配端口,而是将服务的基本 URL 设置为 test server's URL .

如果您确实要设置监听端口,请执行以下操作:

// create a listener with the desired port.
l, err := net.Listen("tcp", "127.0.0.1:8080")
if err != nil {
    log.Fatal(err)
}

ts := httptest.NewUnstartedServer(handler)

// NewUnstartedServer creates a listener. Close that listener and replace 
// with the one we created.
ts.Listener.Close()
ts.Listener = l

// Start the server.
ts.Start()
// Stop the server on return from the function.  
defer ts.Close()

// Add your test code here.  

关于unit-testing - 在 Go 中为 httptest.NewServer 使用自定义 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42214611/

相关文章:

node.js - NodeJS - 默认情况下,http 请求和响应是否在 NodeJS 世界之外流?

apache - 如何在 MODX 中设置 410 HTTP 状态码

go - 如何在进行交叉编译时切换/选择要使用的代码

python - Python中 "renaming files"的单元测试

sharepoint - 在 SharePoint 中对事件处理程序进行单元测试?

php - 在PHP中存储上一页的URL?

google-chrome - 如何使用 Chromedp 打开受 Cloudflare 保护的网站?

go - 无法从 super 账本结构中的链码实例将数据上传到谷歌云存储

node.js - 对所有测试只运行一次 ava test.before()

java - 是否有使用 Groovy 进行单元测试(以及集成或回归,如果适用)的情况?