自定义Go中的测试

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

Customizing the tests in Go

问题

我正在运行GO中的测试用例场景,我知道一个测试文件(例如:first_test.go)在第二次或第三次尝试后会通过。

假设它正在调用数据库连接、调用REST服务或任何其他典型场景。

我正在查看$go test命令中可用的选项,但没有参数可以设置尝试次数。
是否有一种实现文件尝试或从包含任何尝试3-4次方法的静态文件中调用方法的方法,例如对于这种典型的文件场景:

func TestTry(t *testing.T) {
    //连接数据库的代码
}
英文:

I have a scenario running testcases in GO where in I know that a testfile for eg: first_test.go will pass after second or third attempt ,

assuming that it is invoking a connection to a database or calling a REST service or any other typical scenario.

Was going through the options available in the $go test command ,but no parameters are available to many tries.
Is there any way of implementing the tries for a file or calling a method from a static file with contains any method to try 3-4 times, like for this typical file scenario:

func TestTry(t *testing.T) {
	//Code to connect to a database
}

答案1

得分: 2

一个常用的方法是使用构建标记(build flags)。创建一个专门用于集成测试的特殊测试文件,并添加以下内容:

// +build integration
package mypackage

import "testing"

然后运行集成测试:

go test -tags=integration

接下来,你可以添加逻辑:

// +build integration
package testing

import "flag"

var maxAttempts = flag.Int(...)

func TestMeMaybe(t *testing.T) {
    for i := 0; i < *maxAttempts; i++ {
        innerTest()
    }
}

请注意,这只是一个示例,具体的构建标记和逻辑需要根据你的实际需求进行调整。

英文:

One idiom is to use build flags. Create a special test file only for integration test and add

// +build integration
package mypackage
import testing

Then to run the tests for integration run :

go test -tags=integration

And then you can add logic

// +build integration
package testing

var maxAttempts = flag.Int(...)

func TestMeMaybe(t *testing.T){
 for i :=0 ; i &lt; *maxAttempts; i++ {
   innerTest()
 }
}

答案2

得分: 1

不,这将非常奇怪:如果测试有时会随机成功,那有什么好处呢?

为什么不在测试中尝试一下自己呢?真正的测试要么通过,要么失败,你可以根据自己的知识处理“我需要尝试调用这个外部资源n次来唤醒它”的情况。

英文:

No, this would be very strange: What good is a test if it randomly succeeds sometimes?

Why don't you "try" yourself inside the test? The real test either passes or fails and you handle your knowledge about "I need to 'try' calling this external resource n times to wake it up."

答案3

得分: 1

这不是测试的正确方式:测试的目的是告诉你代码是否按预期工作,而不是检查外部资源是否可用。

当使用外部资源(例如网络服务或API)时,最简单的方法是通过进行虚拟调用并返回有效响应来模拟其功能,然后在此基础上运行代码。这样,你就可以对代码进行测试。

英文:

That's not the way test are meant to work: a test is here to tell you if your code is working as expected, not tell if an external resource is available.

The simplest way to do it when using an external resource (a webservice or api, for example) is to mock out it's functionnalities by making fake calls that return a valid response, then run your code on that. Then you will be able to test your code.

huangapple
  • 本文由 发表于 2014年8月21日 15:15:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/25420363.html
匿名

发表评论

匿名网友

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

确定