运行 http.ListenAndServe() On Tests using

我正在尝试为我使用gorilla/muxgorm.iogolang-migrate/v4制作的 REST API 应用程序创建集成测试

对于我正在使用的测试testify

SetupSuite()的我integration_Test.go是这样的:

func (s *ReceiptServiceTestSuite) SetupSuite() {

    s.Require().NoError(godotenv.Load("test.env"))

    s.Require().NoError(database.Connect())

    s.db = database.DB

    s.m = database.M


    router.HandleRequests()

}

而我router.HandleRequests()的是这样的:


func HandleRequests() {

    router := mux.NewRouter()

    router.Use(middleware)

    // lots of router.HandleFunc()

    

    http.ListenAndServe(":8080", router)

}

问题是:如果我router.HandleRequests()从 中删除SetupSuite(),我所有的数据库测试都会正常运行,但是如果我尝试http.ListenAndServe()停止测试工作流并且什么也没有发生。


我相信我应该使用 goroutinesrouter.HandleRequests()以便它可以与测试并行运行,我只是不知道该怎么做。


有关更多信息,这里是项目存储库,我不知道它是否相关,但我正在运行两个 postgres 实例docker-compose,一个用于运行项目,另一个用于测试。


www说
浏览 326回答 1
1回答

FFIVE

我想出了如何使用 goroutines 来做到这一点。我读了这个例子,它教如何处理os.Signals使用渠道,我是这样实现的:首先,我在路由器上进行了以下更改:func HandleRequests() {&nbsp; &nbsp; router := mux.NewRouter()&nbsp; &nbsp; router.Use(middleware)&nbsp; &nbsp; // lots of router.HandleFunc()&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; go http.ListenAndServe(":8080", router)&nbsp; &nbsp; quit := make(chan os.Signal, 1)&nbsp; &nbsp; signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)&nbsp; &nbsp; <-quit}所以现在http.ListenAndServe()正在一个新线程中运行。我相信默认行为会在程序执行结束时停止。之后http.ListenAndServe(),我创建了一个os.Signalchanel,它将监听来自系统的传入信号(SIGINT 和 SIGTERM),然后该函数将停止在<-quit,它将等待一个信号继续。然后我修复了我在 goroutineSetupSuite()中运行:router.HandleRequests()func (s *ReceiptServiceTestSuite) SetupSuite() {&nbsp; &nbsp; s.Require().NoError(godotenv.Load("test.env"))&nbsp; &nbsp; s.Require().NoError(database.Connect())&nbsp; &nbsp; s.db = database.DB&nbsp; &nbsp; s.m = database.M&nbsp; &nbsp; go router.HandleRequests()}在我TearDownSuite()向当前进程发送 SIGTERM 信号时,quit我之前创建的通道将监听该信号,router.HandleRequests()并且该函数将继续终止程序。func (s *ReceiptServiceTestSuite) TearDownSuite() {&nbsp; &nbsp; // some database code&nbsp;&nbsp; &nbsp; p, _ := os.FindProcess(os.Getpid())&nbsp; &nbsp; p.Signal(syscall.SIGINT)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go