Skip to content

Writing integration tests

edeyoung edited this page Dec 11, 2019 · 1 revision
  • Name the file <whatever>_integration_test.go

  • At the top of the test file, include

    // +build integration
    

    This makes it so the integration test only runs if -tag=integration is included in the go test command.

  • Include a TestMain function similar to below:

    func TestMain(m *testing.M) {
      var err error
    
      err = config.SetupConfigForTests()
      if err != nil {
      	panic(err)
      }
    
      err = setup()
      if err != nil {
      	panic(err)
      }
    
      hap := th.HostAndPort{Host: viper.GetString("dbhost"), Port: viper.GetString("dbport")}
      err = th.CheckResources(hap)
      if err != nil {
      	panic(err)
      }
    
      code := m.Run()
    
      teardown()
      os.Exit(code)
    }
    

    The critical pieces are:

    err = config.SetupConfigForTests()
    

    This ensures that you are using the test configuration for your tests. This is very important!

    hap := th.HostAndPort{Host: viper.GetString("dbhost"), Port: viper.GetString("dbport")}
    err = th.CheckResources(hap)
    

    This checks that any of the external resources that the integration tests will be accessing are available.

    code := m.Run()
    ...
    os.Exit(code)
    

    This runs the test suite and then exists with the appropriate error code.

  • Run any test-by-test setup and teardown at the top of each individual test. See the example below for doing this with a database. The setup ensures that the database is empty and the teardown clears out the database prior to the next test.

    teardown, _ := th.IntegrationDBTestSetup(t, store.DB)
    defer teardown(t, store.DB)
    
Clone this wiki locally