How do I test the API in the Golang project?

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

This article starts with my blog

Briefly

In the daily backend business development, we often write some API, and then use the postman test whether it is available, it may be thrown directly to the line. However, the goose is not very rigorous, and in most cases it is necessary to test the API to ensure availability. What I used in the project was httpexpect, something similar to the Mocha in Nodejs. There's no introduction to basic unit tests here, so you can see them by flipping through the Golang Getting Started guide.

Use

Httpexpect is an end-to-end API testing Tool

End-to-end HTTP and REST API testing for Go.

Installation

go get -u -v github.com/gavv/httpexpect

A small example

 package  Example import  ( "net/http"   "net/http/httptest"  " testing " " Github.com/gavv/httpexpect ") func  testfruits  Span class= "Hljs-params" > (t *testing. T)   {//create HTTP. Handler  Handler: = Fruitshandler () //Run server  server: = Httptest. NewServer (handler) defer  server. Close () //Create Httpexpect instance  e: = Httpexpect. New (t, server.    URL) //test API is working  E.get ( "/test" ).    Expect (). Status (http. Statusok). JSON (). Array (). Empty ()}  

Supports JSON data validation

Orange: = map[string]interface{}{"Weight": 100,}//GET creates an orange E. PUT ("/fruits/orange").  Withjson (orange).  Expect (). Status (http. statusnocontent). Nocontent ()//get then get and verify whether the data contains weight:100e. GET ("/fruits/orange").  Expect (). Status (http.  Statusok). JSON (). Object (). ContainsKey ("Weight"). Valueequal ("Weight", +) Apple: = map[string]interface{}{"Colors": []interface{}{"Green","Red"},"Weight": 200,}//Create an apple E. PUT ("/fruits/apple").  Withjson (apple).  Expect (). Status (http. statusnocontent). Nocontent ()//Get this apple obj: = E.get ("/fruits/apple").  Expect (). Status (http. Statusok). JSON (). Object () obj. Keys (). Containsonly ("Colors","Weight")//test obj for the returned data individually. Value ("Colors"). Array (). Elements ("Green","Red") obj. Value ("Colors"). Array (). Element (0). String (). Equal ("Green") obj. Value ("Colors"). Array (). Element (1). String (). Equal ("Red") obj. Value ("Colors"). Array (). First (). String (). Equal ("Green") obj. Value ("Colors"). Array (). Last (). String (). Equal ("Red")

Chain call function is very handy, in fact, there are many built-in functions, the Object data type has the following functions and so on, to meet a variety of testing needs.

ContainsKeyContainsMapEmptyEqualKeysNotContainsKey

Of course, other scenarios are supported for testing, such as

    • JSON Schema and JSON PathJSON mode
    • FormsForm
    • URL constructionURL constructs
    • HTTP HeadersHeader
    • CookiesCookies
    • Regular expressionsRegular
    • Subdomains and per-request URLChild URL
    • Reusable builderscan be reused
    • Custom configCustom
    • Session supportSession Sessions Support
    • Use HTTP handler directlyredirect

Practical application

The following is an example of a dependency on the Gin Framework API project using Httpexpect.

    1. App.go
package mainimport (  "./engine")func main() {  engine.GetMainEngine().Run(":4000")}
    1. Engine/engine.go, there is one more engine.go here because we are going to *gin. The Engine returns to Httpexpect, creating the server, referring to the node. JS Project API test.
 PackageEngineImport("Github.com/gin-contrib/sessions"  "Github.com/gin-gonic/gin") func getmainengine() *gin. Engine {r: = gin. New ()//DB, Store: = database. Connect ()  //LOGDB: = database. Connectlog ()  //R.use (sessions. Sessions ("xxx", store))  //R.use (Corsmiddleware ())  //R.use (gin. Logger ())  //R.use (gin. Recovery ())  //R.use (Requestlogger ())        //A bunch of custom handlerRouters. Init (R)returnR
    1. Articles_test.go
 PackageTestImport("Net/http"  "Testing")varEng *httpexpect. Expect func getengine(t *testing. T) *httpexpect. Expect {gin. SetMode (gin. Testmode)ifEng = =Nil{server: = Httptest. NewServer (engine. Getmainengine ()) eng = Httpexpect. New (t, server. URL)}returnEng func testarticles(t *testing. T) {e: = Getengine (t) e.get ("/api/v1/articles").    Expect (). Status (http.    Statusok). JSON (). Object (). ContainsKey ("Data"). Keys (). Length (). Ge (0)}

And then execute

test -v -cover ...

The execution results are similar:

With this package, we can test each of the RESTful APIs to improve the quality of the code more significantly. Here is my. TRAVIS.YML configuration. Shortcomings, please criticize correct!

Language: GoServices: MongoDBgo:  - 1.9. 2  - MasterInstall: trueMatrix:Allow_failures:-Go: MasterFast_finish: trueNotifications:Email: falseScript:  - Echo "Script"  - Go Get - u - v  Github.com/gavv/httpexpect  - Other Customizations  - Echo "add config file"  - CP Config/config.example.yaml Config/config.yaml  - Echo "Test"  - Export gin_mode=test  - Go Test - v -cover test/*
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.