In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
Today, I will introduce you to write testable better go code sample analysis. The content of the article is good. Now I would like to share it with you. Friends who feel in need can understand it. I hope it will be helpful to you. Let's read it along with the editor's ideas.
When developing an interface, it is usually necessary to introduce database, redis, or other internal services. Unit testing needs to start the corresponding database, redis, and third-party services first, otherwise, it is impossible to do unit testing. The following is to solve this situation, in principle that the underlying related services have undergone rigorous unit testing, so extract the relevant methods, in the unit test, simulate to replace the actual database, redis, or other internal services.
A common example.
Next, a http service is started, which provides a / bad interface. The function of this interface is to receive a parameter args of type string and query the apps through db.
/ better/main.gopackage mainimport ("errors"net/http"better/service"github.com/jinzhu/gorm") func main () {http.HandleFunc ("/ bad", func (w http.ResponseWriter, r * http.Request) {args: = r.URL.Query () .Get ("args") / / init db db Err: = dao.NewStorage () if err! = nil {w.Write ([] byte (err.Error () w.WriteHeader (http.StatusBadRequest) return} apps, err: = service.NewHandle () .GetApps (args Db.DB) if err! = nil {w.Write ([] byte (err.Error ()) w.WriteHeader (http.StatusBadRequest) return} w.Write ([] byte (apps)) w.WriteHeader (http.StatusOK) return}) err: = http.ListenAndServe (": 8080") Nil) if err! = nil {panic (err)}}
Service layer
/ / better/service/bad.gopackage serviceimport ("errors"github.com/jinzhu/gorm") type handle struct {} func NewHandle () * handle {return & handle {} func (h handle) GetApps (args string, db * gorm.DB) (apps string, err error) {if args = "" {return "" Errors.New ("args is nil")} / / introduce db err = db.Find (& apps). Error if err! = nil {return ", err} return apps, nil}
Database layer
/ / better/dao/apps.gopackage daoimport "github.com/jinzhu/gorm" type Storage struct {DB * gorm.DB} func NewStorage () (* Storage, error) {db, err: = gorm.Open ("user:pass@tcp (127.0.0.1 type Storage struct 3306) / dbname?charset=utf8mb4&parseTime=True&loc=Local") if err! = nil {return nil, err} return & Storage {DB: db}, nil} func (s * Storage) GetApps () (string Error) {return "dao apps", nil}
Unit test code
/ / better/service/bad_test.gopackage serviceimport ("testing"github.com/jinzhu/gorm") func Test_GetApps (t * testing.T) {db, err: = gorm.Open ("user:pass@tcp (127.0.0.1 github.com/jinzhu/gorm 3306) / dbname?charset=utf8mb4&parseTime=True&loc=Local") if err! = nil {t.Fatal ("gorm open err", err.Error ())} _, err = NewHandle (). GetApps ("test") Db) if err! = nil {t.Fatal ("getApps err", err.Error ())} t.Log ("success")}
If we were to unit test the func (h handle) getApps (args string, db * gorm.DB) (apps string, err error) method, we would have to start a mysql so that the unit test code is heavily coupled to db. If calling other services is involved inside the method, we have to start other services, which makes the unit test very inconvenient to write.
A better way to implement
Add a new better interface
/ better/main.gopackage mainimport ("net/http"better/dao"better/service"github.com/jinzhu/gorm") func main () {http.HandleFunc ("/ better", func (w http.ResponseWriter, r * http.Request) {args: = r.URL.Query () .Get ("args") / / init db db Err: = dao.NewStorage () if err! = nil {w.Write ([] byte (err.Error () w.WriteHeader (http.StatusBadRequest) return} apps Err: = service.NewBetterHandle (db) .GetApps (args) if err! = nil {w.Write ([] byte (err.Error ()) w.WriteHeader (http.StatusBadRequest) return} w.Write ([] byte (apps)) w.WriteHeader (http.StatusOK) return}) err: = http.ListenAndServe (": 8080") Nil) if err! = nil {panic (err)}}
Service layer
/ better/service/better.gopackage serviceimport "errors" / / better gotype betterHandle struct {Storage BetterHandleStorage} type BetterHandleStorage interface {GetApps () (string, error)} func NewBetterHandle (storage BetterHandleStorage) * betterHandle {return & betterHandle {Storage: storage}} func (h betterHandle) GetApps (args string) (apps string, err error) {if args = = "{return", errors.New ("args is nil")} apps Err = h.Storage.GetApps () if err! = nil {return ", err} return apps, nil}
Unit testing
Package serviceimport ("testing") func Test_BetterGetApps (t * testing.T) {var m DBMock apps, err: = NewBetterHandle (& m) .GetApps ("Test_BetterGetApps") if err! = nil {t.Fatal ("getApps err", err.Error ())} t.Log ("apps:", apps)} type DBMock struct {} / / build mock data / / so we can test our approach There is no need to start a dbfunc (m * DBMock) GetApps () (string, error) {return "mock apps", nil} that is all about writing testable better go code samples and analysis. for more content related to writing testable better go code samples, you can search the previous articles or browse the following articles to learn! I believe the editor will add more knowledge to you. I hope you can support it!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.