How to run test cases in a specified file?

前端 未结 7 1600
孤独总比滥情好
孤独总比滥情好 2020-12-04 05:30

My package test cases are scattered across multiple files, if I run go test it runs all test cases in the package.

It is unnecessar

相关标签:
7条回答
  • 2020-12-04 06:15
    alias testcases="sed -n 's/func.*\(Test.*\)(.*/\1/p' | xargs | sed 's/ /|/g'"
    
    go test -v -run $(cat coordinator_test.go | testcases)
    
    0 讨论(0)
  • 2020-12-04 06:16

    in intelliJ IDEA go-lang plugin (and i assume in jetbrains Gogland) you can just set the test kind to file under run > edit configurations

    0 讨论(0)
  • 2020-12-04 06:18

    @zzzz's answer is mostly complete, but just to save others from having to dig through the referenced documentation you can run a single test in a package as follows:

    go test packageName -run TestName
    

    Note that you want to pass in the name of the test, not the file name where the test exists.

    The -run flag actually accepts a regex so you could limit the test run to a class of tests. From the docs:

    -run regexp
        Run only those tests and examples matching the regular
        expression.
    
    0 讨论(0)
  • 2020-12-04 06:20

    When running a single test I usually do:

    go test -run TestSomethingReallyCool ./folder1/folder2/ -v -count 1
    

    -count 1 also ensures that the test is ran every time instead of being cached. Useful when you are testing against race conditions and have a test that fails only sometimes. In Go versions not using modules the same could be achieved by setting GOCACHE=off but this interacts poorly with Go modules.

    0 讨论(0)
  • 2020-12-04 06:20
    go test -v -timeout 30s <path_to_package> -run ^(TestFuncRegEx)
    
    • The TestFunc must be inside a go test file in that package
    • We can provide a regular expression to match a set of test cases or just the exact test case function to run a single test case. For instance -run TestCaseFunc
    0 讨论(0)
  • 2020-12-04 06:31

    There are two ways. The easy one is to use the -run flag and provide a pattern matching names of the tests you want to run.

    Example:

    $ go test -run NameOfTest
    

    See the docs for more info.

    The other way is to name the specific file, containing the tests you want to run:

    $ go test foo_test.go
    

    But there's a catch. This works well if:

    • foo.go is in package foo.
    • foo_test.go is in package foo_test and imports 'foo'.

    If foo_test.go and foo.go are the same package (a common case) then you must name all other files required to build foo_test. In this example it would be:

    $ go test foo_test.go foo.go
    

    I'd recommend to use the -run pattern. Or, where/when possible, always run all package tests.

    0 讨论(0)
提交回复
热议问题