简体   繁体   中英

Run a single Golang httptest server for all tests on different packages

My project folder is something like this. It a large API, I separate the files for organization pourposes only.

$ tree src/backend/

src/backend/
├── cats
│   ├── cat_test.go
│   ├── handler.go
│   ├── routes.go
│   └── tools.go
├── cmd
│   ├── populate.go
│   ├── root.go
│   └── runserver.go
├── iot
│   └── device
│      ├── all.go
│      ├── all_test.go
│      ├── router.go
│      ├── types.go
│      └── update.go
├── main.go
├── main_test.go
└── root_test.go

On main_test.go I start the httptest server

func TestMain(m *testing.M) {
    setup()
    exitVal := m.Run()
    teardown()
    os.Exit(exitVal)
}

func setup() {
    flag.StringVar(&util.ServerFlag, "server", "s", "server to set request for")
    flag.Parse()
    viper.SetDefault("testing", true)
    util.BasicStart()
    iot.RunDependencies()
    cats.SyncS3()
    router := cmd.InitRootRouter()
    util.SetTestServer(httptest.NewServer(router))
}

func teardown() {
    log.Println("[TESTS] - Teardown completed")

}

All the tests on root_test.go work perfctly when I run go test -v ./src/backend/... . But the test at src/backend/cat_test.go fail due to the fact that the teardown method has already been called by the time they run. How can I make the server wait for all test to be run before shutting down?

Each package's tests run as a separate binary, so there is no way to share setup and teardown state between packages. If you have a complex setup or teardown that you need to share across packages then you can create a testing package in your project which defines the test scaffold and call it from each test's setup and teardown .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM