How to run golang tests sequentially?

前端 未结 4 1034
情歌与酒
情歌与酒 2020-12-03 11:10

When I run go test, my output:

--- FAIL: TestGETSearchSuccess (0.00s)
        Location:       drivers_api_test.go:283
        Error:          No         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 11:39

    Apart for 3rd party libraries like Convey and Ginkgo, with plain Golang 1.7 you can run tests sequentially. You can read more here

    func TestFoo(t *testing.T) {
        // 
        t.Run("A=1", func(t *testing.T) { ... })
        t.Run("A=2", func(t *testing.T) { ... })
        t.Run("B=1", func(t *testing.T) { ... })
        // 
    }
    

    And you can run them conditionally with:

    go test -run ''      # Run all tests.
    go test -run Foo     # Run top-level tests matching "Foo", such as "TestFooBar".
    go test -run Foo/A=  # For top-level tests matching "Foo", run subtests matching "A=".
    go test -run /A=1    # For all top-level tests, run subtests matching "A=1".
    

    So lets say you got an user package from a REST api that you want to test. You need to test the create handler in order to be able to test the login handler. Usually I would have this on the user_test.go

    type UserTests struct { Test *testing.T}
    func TestRunner(t *testing.T) {
    
        t.Run("A=create", func(t *testing.T) {
            test:= UserTests{Test: t}
            test.TestCreateRegularUser()
            test.TestCreateConfirmedUser()
            test.TestCreateMasterUser()
            test.TestCreateUserTwice()
        })
        t.Run("A=login", func(t *testing.T) {
            test:= UserTests{Test: t}
            test.TestLoginRegularUser()
            test.TestLoginConfirmedUser()
            test.TestLoginMasterUser()
        })
    
    }
    

    Then I can append methods to the UserTest type that wont be executed by the go test command in any _test.go file

    func (t *UserTests) TestCreateRegularUser() {
        registerRegularUser := util.TableTest{
            Method:      "POST",
            Path:        "/iot/users",
            Status:      http.StatusOK,
            Name:        "registerRegularUser",
            Description: "register Regular User has to return 200",
            Body: SerializeUser(RegularUser),
        }
        response := util.SpinSingleTableTests(t.Test, registerRegularUser)
        util.LogIfVerbose(color.BgCyan, "IOT/USERS/TEST", response)
    }
    

提交回复
热议问题