unit-testinggo

Is it possible to print golang unit test results out to a file?


I run go test in my pkg directory and I get the test results printed to the console as they run, but it would be ideal if I could get them printed to a txt file or even a html file, is it possible to do this? I know you can get coverage reports out from it and generate html files for those which is excellent, but I would have thought it possible to do the same just for the actual results of the tests i.e which tests ran, which passed and which failed. I've been searching the net but even go test help doesn't offer any suggestions for printing results out to a file.


Solution

  • 2018: Go 1.10+

    As noted in Yoshiki Shibukawa's answer, you have cmd/test2json

    go tool test2json [-p pkg] [-t] [./pkg.test -test.v=test2json]
    

    Other approaches around go tool test2json:


    2015: Since I only want to see failed test, I have this script "gt" that I run instead of go test:

    go test -coverprofile=coverage.out %*|grep -v -e "^\.\.*$"|grep -v "^$"|grep -v "thus far"
    

    That way, it filters everything but the failed cases.
    And you can redirect its content to a file, as mentioned: gt > test.out

    It also generates code coverage, which is why I have another script "gc":

    grep -v -e " 1$" coverage.out
    

    That way, I don't even wait for a brower to open, I directly see the list of lines which are not yet covered (ie, which don't end with ' 1' in the coverage.out file)