如何在Go Playground中使用测试包?

huangapple go评论141阅读模式
英文:

How do I use the testing package in go playground?

问题

testing包在Go Playground中是可用的。

如果没有访问go test的权限,你可以如何使用Go Playground来演示测试概念呢?

我的假设是可以使用testing.RunTests函数来实现。然而,我的尝试总是只生成“testing: warning: no tests to run”的结果。

示例:https://play.golang.org/p/PvRCMdeXhX

为了提供背景,我的使用场景是与同事分享快速测试、示例和基准的代码片段。我经常依赖Go Playground来分享这样的代码片段。

英文:

The testing package is available in the go playground.

How can I use the go playground to demonstrate testing concepts, without access to go test?

My assumption is it's possible using the testing.RunTests function. My attempts to do so always generate only "testing: warning: no tests to run".

Example: https://play.golang.org/p/PvRCMdeXhX

For context, my use case is for sharing quick examples of tests, examples and benchmarks with colleagues. I rely on go playground for sharing code snippets like this often.

答案1

得分: 13

你需要使用testing.Main

func main() {
    testSuite := []testing.InternalTest{
        {
            Name: "TestCaseA",
            F:    TestCaseA,
        },
    }
    testing.Main(matchString, testSuite, nil, nil)
}

如果你想使用“非废弃”的但不稳定的方式:

https://play.golang.org/p/4zH7DiDcAP

英文:

You need to use testing.Main:

func main() {
	testSuite := []testing.InternalTest{
		{
			Name: "TestCaseA",
			F:    TestCaseA,
		},
	}
	testing.Main(matchString, testSuite, nil, nil)
}

https://play.golang.org/p/DQsIGKNWwd

If you want to use the "non deprecated", but unstable way:

https://play.golang.org/p/4zH7DiDcAP

答案2

得分: 4

Dave的回答仍然可以作为手动调用测试的方法,但是如果你阅读了“关于”部分,现在测试是自动支持的:

> 如果程序包含测试或示例但没有主函数,服务将运行这些测试。由于程序在受限资源的沙盒环境中运行,可能不支持基准测试。

英文:

Dave's answer still works as a manual way of invoking tests, but if you read the "About" tests are now automatically supported:

> If the program contains tests or examples and no main function, the service runs the tests. Benchmarks will likely not be supported since the program runs in a sandboxed environment with limited resources.

答案3

得分: 0

在 playground 上有执行时间限制,我相信它们比 bench 使用的最小执行时间要少。从审查 go test 命令的源代码来看,当前适合测试的正确入口是 testing.MainStart,你可能会或者不会使用它。它在技术上是一个内部使用的 API,不受兼容性指南的约束,所以结果可能会有所不同。

英文:

There are execution time limits on playground and I believe they are less than the minimum execution time used by bench. From reviewing the source of the go test command, it looks like the current proper entry point for tests is testing.MainStart which you may or may not have luck using. It is technically an internal-use API and not subject to compatibility guidelines, so YMMV.

huangapple
  • 本文由 发表于 2017年9月14日 04:00:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/46205923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定