Test the Go language Web app

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed. [Image] (https://raw.githubusercontent.com/studygolang/gctt-images/master/testing-web-app/cover.jpg) I use my spare time to try to use Go To write a website small app. There are some great packages in the Go standard library that can be used in WEB application development and I like to use them very much. In fact, there's a small tutorial on the official Go wiki that writes Web apps. However, there is no mention of how to test WEB applications with a standard library, and there is no better way to find a solution. In the spirit of trying to do some of my own projects, I found that the key to testing WEB applications in the Go language is to implement dependency injection by using advanced functions. # # Dependency Injection through [dependency injection] (https://en.wikipedia.org/wiki/Dependency_injection) We want to achieve a goal that can support all of our functional requirements. However, at first it was not clear how to do it. Most tutorials will write a WEB application like this: "' Gopackage mainimport (" FMT "" Net/http ") Func handler (w http). Responsewriter, R *http. Request) {fmt. fprintf (W, "Hi there, I love%s!", R.url. Path[1:])}func main () {http. Handlefunc ("/", handler) HTTP. Listenandserve (": 8080", nil)} ' source: [Writing a WEB application-Golang Wiki] (https://golang.org/doc/articles/wiki/) doesn't mean it's a bad deal. , but we want to know what happens when you add a database? or an external package to manipulate our sessions, like [Gorilla Session] (https://github.com/gorilla/sessions)? Typically, people instantiate a database to manage or manipulate a global session and set the validity period to one day. But this will cause you trouble when you try to test. It's a good idea to write a function to create a related action for you. "' Gopackage maInimport ("FMT" "Net/http" "github.com/markberger/database") type Appdatabase interface {Getbacon () String}func Homehandler (DB appdatabase) http. Handler {return HTTP. Handlerfunc (Func (w http. Responsewriter, R *http. Request) {fmt. fprintf (W, "Hi there, I love%s!", db. Getbacon ())})}func main () {db: = database. Newdatabase () http. Handlefunc ("/", Homehandler (db)) HTTP. Listenandserve (": 8080", nil)} "is very good, because then we no longer need global variables." And it's very easy to mocking (translator note: Use a dummy object to create a test method for testing). We can simply create a database mock to meet the data requirements of the interface just by implementing the ' Getbacon ' method. # # Test Now we need a project to start writing our tests. The key is to test ' http. Handler ', with the ' httptest ' in the [Net/http/httptest] (https://golang.org/pkg/net/http/httptest/) package. Responserecorder ' inside the method. "' Gopackage mainimport (" Net/http "" Net/http/httptest "" testing ") type MOCKDD struct {}function (db mockdb) Getbacon () {R Eturn "Bacon"}function testhome (t *testing. T) {mockdb: = mockdb{} homehandle: = Homehandler (MOCKDB) req, _: = http. Newrequest ("GET", "", nil) W: = Httptest. Newrecorder () homehandle.servehttp (W, req)If W.code! = http. Statusok {T.errorf ("Home page didn ' t return%v", http. Statusok)}} "" Of course, the code is well reused, especially when the POST request is tested. Therefore, I have been using these methods to perform test operations. "' Gopackage mainimport (" Net/http "" Net/http/httptest "" Net/url "" testing ") type Handletester func (method string, param S URL. Values,) *httptest. responserecorder//Given The current Test runner and an HTTP. Handler, generate a//handletester which would test its given input against the//Handler.func Generatehandletester (t *tes Ting. T, Handlefunc http. Handler,) Handletester {//Given a method type ("GET", "POST", etc) and//parameters, serve the response against the Han Dler and//return the Responserecorder. return func (method string, params URL. Values,) *httptest. Responserecorder {req, err: = http. Newrequest (Method, "", Strings. Newreader (params. Encode ()),) if err! = Nil {T.errorf ("%v", Err)} req. Header.set ("Content-type", "application/x-www-form-urlencoded; Param=value ",) W: = Httptest. Newrecorder () handlefunc.servehttp (W, req) Return W }}function testhome (t *testing. T) {mockdb: = mockdb{} homehandle: = Homehandler (mockdb) Test: = Generatehandletester (T, homehandle) W: = Test ("GET", url . values{}) if W.code! = http. Statusok {T.errorf ("Home page didn ' t return%v", http. Statusok)}} "For more relevant detailed usage, you can [click] (https://github.com/markberger/carton/blob/master/api/auth_test.go) To view my small project. If you have a better way to use the standard library for Web application testing, you can always leave a message or send me an email.

via:http://markjberger.com/testing-web-apps-in-golang/

Author: Mark J. Berger Translator: Zhucheer proofreading: polaris1119

This article by GCTT original compilation, go language Chinese network honor launches

This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove

525 Reads
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.