我通过在 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/