Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 429
Kumaran Senapathy Avatar asked Feb 13 '17 22:02

Kumaran Senapathy


1 Answers

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()

// Run your tests here.

// Cleanup.
ts.Close()
like image 58
Bayta Darell Avatar answered Oct 04 '22 05:10

Bayta Darell