简体   繁体   中英

Using custom URL for httptest.NewServer in Go

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?

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.  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM