首页 > 其他分享 >Go - Testing a Web Application or a Web Service

Go - Testing a Web Application or a Web Service

时间:2023-10-18 19:11:06浏览次数:30  
标签:function Web http Testing test handler httptest Go ResponseWriter

Problem: You want to do unit testing on a web application or a web service.


Solution: Use the httptest.NewRecorder function to create an httptest.ResponseRecorder that can be used to record what’s been written to the http.ResponseWriter . This can then be used to test the response.

 

Web applications and web services are the most popular type of programs written in Go, so obviously you need to be able to test them. The httptest package provides a way to do this.

The handler function is the function that is called when a request is received. The handler function writes the response to the http.ResponseWriter , which is then passed back to the client. This approach focuses on testing the handler function that is used to handle the request, which covers most of what you need. Specific functions can be tested using the normal approach, but testing the handler is a bit tricky because you need to create an HTTP server to test it.

The httptest.NewRecorder function creates an httptest.ResponseRecorder that implements the http.ResponseWriter interface. This can be used to record what’s been written to the http.ResponseWriter so that you can test the response:

Let's say we have this handler function we want to test:

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello  World!")
}

You can test this using the httptest package like this:

func TestHttpHello(t *testing.T) {
    http.HandleFunc("/hello", hello)
    writer := httptest.NewRecorder()
    request, _ := http.NewRequest("GET", "/hello", nil)
    http.DefaultServeMux.ServeHTTP(writer, request)
    if writer.Code != http.StatusOK {
        t.Errorf("Response  code  is  %v", writer.Code)
    }
    if expected, actual := "Hello  World!", writer.Body.String(); expected != actual {
        t.Errorf("Response  body  is  %v", actual)
    }
}

First, you need to register the handler function with the http.DefaultServeMux using the http.HandleFunc function. This is the same way you would register the handler function normally. Then you create an httptest.ResponseRecorder using the httptest.NewRecorder function. This implements the http.ResponseWriter interface.

Next, you need to create the client to emulate someone sending an HTTP request to the server. Use the http.NewRequest function to create a GET request to the /hello URL. With this, you have both the http.ResponseWriter and http.Request that you can pass to ServeHTTP to dispatch the request to the handler function that matches the URL. Remember, when you registered the handler function using http.HandleFunc , you actually registered the function to http.DefaultServeMux . This is the same multiplexer you are using to dispatch the request.

Once the request is dispatched, the response is written to the ht⁠tpt⁠est.⁠Resp⁠onseRe⁠cor⁠der that you created. You can then test the response code and the response body to make sure that the response is what you expect.

The httptest.ResponseRecorder has a Code field that contains the HTTP status code that was written to the http.ResponseWriter . You can test this to make sure it’s the expected value. The httptest.ResponseRecorder also has a Body field that contains the response body that was written to the http.ResponseWriter . You can test this as well to make sure it’s the expected value. You can also test for other parts of the response, such as the headers, cookies, etc.

 

标签:function,Web,http,Testing,test,handler,httptest,Go,ResponseWriter
From: https://www.cnblogs.com/zhangzhihui/p/17773113.html

相关文章

  • Go - Generating Random Test Inputs for Tests
    Problem: Youwanttogeneraterandomtestdataforrunningyourtestfunctions. Solution: Usefuzzing,whichisanautomatedtestingtechniquetogeneraterandomtestdataforyourtestfunctions. Fuzzing,orfuzztesting,isanautomatedtestingte......
  • RunnerGo 支持UI自动化的测试平台
    RunnerGo提供从API管理到API性能再到可视化的API自动化、UI自动化测试功能模块,覆盖了整个产品测试周期。RunnerGoUI自动化基于Selenium浏览器自动化方案构建,内嵌高度可复用的测试脚本,测试团队无需复杂的代码编写即可开展低代码的自动化测试。 以一条简单的搜索场景为例,本文......
  • WebSocket API 解析:从入门到精通
    WebSocketAPI详解WebSocketAPI是HTML5标准化之后的一项 API,它可用于建立客户端和服务器之间的双向通信连接。WebSocket构造函数用于创建并返回一个 WebSocket 对象。示例://创建WebSocket对象,并指定服务端地址varws=newWebSocket("ws://localhost:8080");WebSocket.r......
  • ZEGO音视频服务的高可用架构设计与运营
      前言:ZEGO即构科技作为一家实时音视频的提供商,系统稳定性直接影响用户的主观体验,如何保障服务高可用且用户体验最优是行业面临的挑战,本文结合实际业务场景进行思考,介绍 ZEGO即构在高可用架构和运营上所进行的探索和实践,希望对大家能有所帮助或启发。一、背景与挑战全......
  • WebRTC 简单入门与实践
     一、前言WebRTC技术已经广泛在各个行业及场景中被应用,但对多数开发者来说,实时音视频及相关技术却是比较不常接触到的。做为一名Web开发者,WebRTC这块的概念着实花了不少时间才搞明白,一是WebRTC本身有较多的独有概念,二是虽然带“Web”字样,但依赖底层概念和网络却是Web......
  • java web(2)
    1.异常全局处理2.事务3.aop技术4.mtbits5.三大存储技术1.异常全局处理点击查看代码importcom.example.program.pojo.Result;importorg.springframework.web.bind.annotation.ExceptionHandler;importorg.springframework.web.bind.annotation.RestControllerAdvice;......
  • 2023-10-18:用go语言,给定一个数组arr,长度为n,表示有0~n-1号设备, arr[i]表示i号设备的型
    2023-10-18:用go语言,给定一个数组arr,长度为n,表示有0~n-1号设备,arr[i]表示i号设备的型号,型号的种类从0~k-1,一共k种型号,给定一个k*k的矩阵map,来表示型号之间的兼容情况,map[a][b]==1,表示a型号兼容b型号,map[a][b]==0,表示a型号不兼容b型号,兼容关系是有向图,也就是a型号兼容b型号......
  • Django修改数据库数据的两种方式
    部分代码展示:fromdjango.shortcutsimportrender,HttpResponse,redirectfromapp01importmodelsdefedit_user(request):#获取url问好后面的参数edit_id=request.GET.get('user_id')#查询当前用户想要编写的数据对象edit_obj=models.User.ob......
  • Go - Creating Subtests to Have Finer Control Over Groups of Test Cases
    Problem: Youwanttocreatesubtestswithinatestfunctiontohavefinercontrolovertestcases.Solution: Usethet.Runfunctiontocreatesubtestswithinatestfunction.Subtestsextendtheflexibilityoftestfunctionstoanotherleveldown. When......
  • Go泛型全面讲解:一篇讲清泛型的全部
    @目录序言1.一切从函数的形参和实参说起2.Go的泛型3.类型形参、类型实参、类型约束和泛型类型3.1其他的泛型类型3.2类型形参的互相套用3.3几种语法错误3.4特殊的泛型类型3.5泛型类型的套娃3.6类型约束的两种选择3.7匿名结构体不支持泛型4.泛型receiver4.1基于泛型的队......