去lang测试事件监听器?

This question is about Go language testing. As you probably know most of mainstream languages have their own xUnit frameworks. Most of these frameworks have an ability to listen to test run events (e.g. test case started, test case finished, test failed and so on). This is often called test event listener and is mainly used when writing third-party extensions for frameworks.

My question: is there any similar way to attach to standard Go language testing framework events (http://golang.org/pkg/testing/)?

Not out of the box, but it shouldn't be hard to rig up yourself. Any function named init is guaranteed to be run before anything else, and that's true for tests as well.

In your test file:

var listener pkg.EventListener
func init() {
    pkg.SetupMyFramework()
    listener = pkg.Listener()
}

Then in any test

func TestXxx(t *testing.T) {
    listener.Dispatch(pkg.MakeEvent("TestXxx", pkg.TestStarted))

    err := DoSomething()
    if err != nil {
        listener.Dispatch(pkg.MakeEvent("TestXxx", pkg.TestFailed))
        t.Fatal("Test failed")
    }

    listener.Dispatch(pkg.MakeEvent("TestXxx", pkg.TestPassed))
}

You can, of course, extend this however you want (using channels, making wrapper functions around Fatal to make this less verbose, etc), but that's the gist of how you can integrate it.


Edit: I wrote a really simple wrapper over *testing.T and an event dispatching framework here: https://github.com/Jragonmiris/testevents

It's totally untested (heh), but it should be relatively close to what you want. It aims to require only one or two extra method calls per test to hook up the dispatching code.

Not that I know of. It would help to know what you are trying to accomplish such that you need this capability?

go1.10 is going to be released soon, and one new feature is go test -json (release notes https://tip.golang.org/doc/go1.10#test).

Using go test -json you can parse the test output and send it to a third party framework.