How to test Gin-gonic controller properly? - Stack Overflow
文章推薦指數: 80 %
Golang Gin-Gonic Split Routes into Multiple Files ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore HowtotestGin-goniccontrollerproperly? AskQuestion Asked 10monthsago Active 10monthsago Viewed 755times 0 I'mlearninggolangbyusingGin-gonicashttphandlerframework.IhaveacontrollerforanendpointwhichmakesoperationswithmyownEmailstructasfollowing: funcEmailUserVerification(c*gin.Context){ varinputvalidators.EmailUserVerificationValidator iferr:=c.ShouldBindJSON(&input);err!=nil{ c.JSON(http.StatusBadRequest,gin.H{"error":err.Error()}) return } email:=models.Email{ To:input.To, Subject:input.Subject, Template:"user_verification.html", TemplateData:notices.EmailUserVerificationTemplateData{ Name:input.Name, VerificationLink:input.VerificationLink, }, Sender:models.NewEmailSMTPSender(input.From), } iferr:=email.Deliver();err!=nil{ panic(err) } c.JSON(http.StatusCreated,nil) } StructEmailisalreadytest,neverthelessIdonotknowhowtotestthismethodproperly.howitissupposedEmailstructtobemockedhere? Iregisteredthehandlerasgin-gonicdocumentationsay: router.POST("/emails/users/verify",controllers.EmailUserVerification) MaybecouldIinjectanEmailinterfaceinthehandler?ifitisthecase,howcanIinjectit? Thanksinadvance^^ gogo-gin Share Improvethisquestion Follow askedFeb7at17:18 AlvaroGarciaAlvaroGarcia 911silverbadge11bronzebadge 1 github.com/gin-gonic/gin#testing – stevenferrer Feb8at2:36 Addacomment | 1Answer 1 Active Oldest Votes 0 Youcantestingitbycreatingtestfilethathavetestingfunctioninsideitandmockothercallingfunction. FormeIusetestify/mocktomockingfunc(forfurtherexplanation,youshouldreadingfromothersitefirstlikemediumandGitHubmockrepo) Forexample IfIhaveroutepathlikethis v1.POST("/operators/staffs",handler.CreateStaff) andhavefunctionhandler.CreateStaffthatinsidecallfunchandler.OperatorStaffUseCase.CreateStaff Iwillcreatefilecreate_staff_test.gothatshouldlooklikethis packageoperator_staff import( "encoding/json" "fmt" "github.com/gin-gonic/gin" "github.com/golang/mock/gomock" jsoniter"github.com/json-iterator/go" "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "net/http" "net/http/httptest" "onboarding-service/app/entities" staffUseCaseMock"onboarding-service/app/mocks/usecases" "strings" "testing" ) funcTestStaffHandler_CreateStaff(t*testing.T){ var( invitationId="3da465a6-be13-405e-a653-c68adf59f2be" firstName="Tom" lastName="Sudchai" roleId=uint(1) roleName="role" operatorCode="velo" email="[email protected]" password="P@ssw0rd" hashedPassword="$2y$12$S0Gbs0Qm5rJGibfFBTARa.6ap9OBuXYbYJ.deCzsOo4uQNJR1KbJO" ) gin.SetMode(gin.TestMode) ctrl:=gomock.NewController(t) deferctrl.Finish() staffMock:=staffUseCaseMock.NewMockOperatorStaffUseCase(ctrl) executeWithContext:=func(mockUseCase*staffUseCaseMock.MockOperatorStaffUseCase,jsonRequestBody[]byte,operatorCodestring)*httptest.ResponseRecorder{ response:=httptest.NewRecorder() context,ginEngine:=gin.CreateTestContext(response) requestUrl:="/v1/operators/staffs" httpRequest,_:=http.NewRequest("POST",requestUrl,strings.NewReader(string(jsonRequestBody))) NewEndpointHTTPHandler(ginEngine,mockUseCase) ginEngine.ServeHTTP(response,httpRequest) returnresponse } createdStaffEntity:=entities.OperatorStaff{ ID:roleId, FirstName:firstName, LastName:lastName, Email:email, Password:hashedPassword, Operators:[]entities.StaffOperator{{ OperatorCode:operatorCode,RoleID:roleId, }}, } t.Run("Happy",func(t*testing.T){ jsonRequestBody,_:=json.Marshal(createStaffFromInviteRequestJSON{ InvitationId:invitationId, FirstName:firstName, LastName:lastName, Password:password, ConfirmPassword:password, }) staffMock.EXPECT().CreateStaff(gomock.Any(),gomock.Any()).Return(&createdStaffEntity,nil) res:=executeWithContext(staffMock,jsonRequestBody,operatorCode) assert.Equal(t,http.StatusOK,res.Code) }) } youwillsee firstmockingfuncwheninitiallytest staffMock:=staffUseCaseMock.NewMockOperatorStaffUseCase(ctrl) andcallininsidetestcasehappycase staffMock.EXPECT().CreateStaff(gomock.Any(),gomock.Any()).Return(&createdStaffEntity,nil) thatismockingfunctionthatwillreturnvalueasIwant(againyoushouldreadmoreaboutgomockandyouwillunderstandwhatItryingtosay) orforeasywaytolearnabouttestingisfallowthistutorial https://github.com/JacobSNGoodwin/memrizr Share Improvethisanswer Follow editedFeb9at9:58 answeredFeb9at9:49 KwiKwi 10222silverbadges1111bronzebadges Addacomment | YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedgogo-ginoraskyourownquestion. GoLanguage Collective LearnmoreaboutCollectivesonStackOverflow TheOverflowBlog Podcast400:AnoralhistoryofStackOverflow–toldbyitsfoundingteam MillineryontheStack:JoinusforWinter(Summer?)Bash,2021! FeaturedonMeta NewresponsiveActivitypage PlannedmaintenancescheduledforThursday,16December01:30UTC(Wednesday... A/BtestingontheAskpage Related 1062 HowtocheckifamapcontainsakeyinGo? 2 GET/articles/:article_idNotworkingGin-Gonic/Gin 11 Doesgin-gonicprocessrequestsinparallel? 7 GinGonicarrayofvaluesfromPostForm 2 AxiosPOSTonGin-Gonic(golang)ServerNotWorking 3 Syntaxquestionfrom`gin-gonic`documentation 0 Gin-Gonicv1.4.0:ctx.FullPath()missing 1 ProblemwithinstallationofGinvia'gogetgithub.com/gin-gonic/gin' HotNetworkQuestions DoestheLog4jvulnerabilityaffectAndroidusers? AoCG2021Day15:LeapfrogSanta DoesApacheWebserveruselog4j(CVE-2021-44228)? Doesachangelinggaintheabilitiesoftheraceitshapeshiftsinto? Dopersonsaccusedofbeing"enemycombatants"havetherighttoaspeedytrial,orcantheUSgovernmentholdthemforaslongasthegovtwishes? AmIprotectedfromLog4jvulnerabilityifIrunJava8u121ornewer? Whydoesthefirstelementoutsideofadefinedarraydefaulttozero? Withoutsaying"crossproduct"explainwhythereisaskew-symmetricangularmomentumtensor Whataresomeinteresting/importantProgrammingLanguageConceptsIcouldteachmyselfinthecomingsemester? Howdoesthelog4shellvulnerabilitywork? Whydoesn'tJamesWebbhavealargersupplyofthrusterpropellant? Howmightnuclearpowerhaveneverbeendeveloped? Slipstreaming-isthereapenalty? Whatisthisseddoingwiththescript:`$a\`? Whydoweneedverylargestationarytelescopesinadditiontotheorbitaltelescopes? Whendoweneed'are'ingermansentences? HasLSD'beenwidelyusedinhospitalsforthetreatmentofmentaldisorders'? Isitascamifanon-AmazonmerchantsendstwoitemsfromAmazonwhenIorderedone? Bassscore,whatdoes"Maybequarternotes"mean? DoesCVE-2021-44228impactLog4jports? Whatisthelawaboutadultsdatingaminor? WhyisADinLatinandBCisinEnglish? Expl3tokenlistwithUTF-8characters(orseeingitasabytelist) CanGodactagainstHiswill? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-golang Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1一起幫忙解決難題,拯救IT 人的一天
Day24 Gin with Cache ... 而我們這章節主要也是在講Gin在Server Cache的實作! ... "github.com/gin-gonic/gin" "ironman...
- 2使用gin封装一个web脚手架(一):控制器和路由 - 掘金
创建一个go项目,名称为myGin go.mod文件为安装gin 创建一个main.go文件创建routes文件夹和controller 项目结构为在controller下创建一个Index控制.
- 3gin+gorm+router 快速搭建crud restful API 接口| Go 技术论坛
根据上一篇"gorm基础"封装crud api接口下载扩展go get github.com/go-sql-driver/mysql go get github.com/jinzhu/gorm ...
- 4sqrtcat/easy-gin: 一套基于Gin 框架的MVC 脚手架 - GitHub
Contribute to sqrtcat/easy-gin development by creating an account on GitHub. ... index.html - ind...
- 5gin controller 自动注册 - 简书
反射入门可以先看这个http://colobu.com/2015/09/23/laws-of-goang-reflection/ 因为在使用gin框架,在配置路由的时候需要手...