Go: how to run tests for multiple packages?

后端 未结 4 1993
别那么骄傲
别那么骄傲 2020-12-31 07:33

I have multiple packages under a subdirectory under src/, running the tests for each package with go test is working fine.

When trying to run all tests

4条回答
  •  忘掉有多难
    2020-12-31 08:04

    I am assuming that because the packages individually pass that in this situation you are also dropping the DB before that test as well.

    Therefore it sounds like the state of the DB for each package test is expected to be empty.
    So between each set of the package tests the DB must be emptied. There are two ways around this, not knowing your entire situation I will briefly explain both options:

    Option 1. Test Setup

    Add an init() function to the start of each package _test file which you then put processing to remove the DB. This will be run before the init() method of the actual package:

    func init() {
        fmt.Println("INIT TEST")
        // My test state initialization
        // Remove database contents
    }
    

    Assuming that the package also had a similar print line you would see in the output (note the stdout output is only displayed when the a test fails or you supply the -v option)

    INIT TEST
    INIT PACKAGE
    

    Option 2. Mock the database

    Create a mock for the database (unless that is specifically what you are testing). The mock db can always act like the DB is blank for the starting state of each test.

提交回复
热议问题