英文:
Using custom URL for httptest.NewServer in 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 testServer.Close()
    student1 := base.getStudent("123")
    log.Print("testServerUrl", testServer.URL) //每次运行时都会打印出 http://127.0.0.1:49931(端口会随机变化)
    testServer.URL = "http://127.0.0.1:8099" //这个赋值并不能改变创建的测试服务器的URL。
}
在被测试的文件中:
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函数是从我的测试中调用的。
这个代码创建了一个新的测试服务器,并在一个随机端口上运行调用。我能否将该服务器运行在我指定的端口上?
英文:
I am running UT on some rest calls by creating a http test server in the Go language. My code is as follows.
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.
}
In the file being tested,
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)
}
This init is called from my test.
This creates a new test server and runs the calls on a random port. Is it possible for me to run this server on a port I specify?
答案1
得分: 30
大多数应用程序使用NewServer或NewUnstartedServer分配的端口,因为这些端口不会与机器上正在使用的端口冲突。它们不会分配一个端口,而是将服务的基本URL设置为test server的URL。
如果你确实想要设置监听端口,请按照以下步骤进行操作:
// 使用所需的端口创建一个监听器。
l, err := net.Listen("tcp", "127.0.0.1:8080")
if err != nil {
log.Fatal(err)
}
ts := httptest.NewUnstartedServer(handler)
// NewUnstartedServer创建一个监听器。关闭该监听器并替换为我们创建的监听器。
ts.Listener.Close()
ts.Listener = l
// 启动服务器。
ts.Start()
// 在函数返回时停止服务器。
defer ts.Close()
// 在这里添加你的测试代码。
英文:
Most applications use the port assigned in NewServer or NewUnstartedServer because this port will not conflict with a port in use on the machine. Instead of assigning a port, they set the base URL for the service to the test server's URL.
If you do want to set the listening port, do the following:
// 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.  
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论