Golang无法在同一个包中进行测试。

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

Golang not able to test in same package

问题

我遇到了一个问题,无法创建一个源文件(commonutil.go)的单元测试。

package util

import "github.com/nu7hatch/gouuid"

// GenerateUUID 返回生成的 UUID 序列
func GenerateUniqueID(hostname string) (string, error) {
    var result, err = uuid.NewV4()
    return hostname + ":" + result.String(), err
}

对于上述的源代码,我创建了一个名为 "commonutil_test.go" 的测试文件(在同一个包中)。

package util

import "testing"

func TestCommonUtil(t *testing.T) {
    t.Run("Test generate UUID", func(t *testing.T) {
        var uuid, _ = GenerateUniqueID("test")
        //fmt.Printf("UUID isa %v \n", uuid)
        if uuid == "" {
            t.Errorf("UUID expected, but result is empty")
        }
    })
}

然而,当我尝试执行 "go test util/commonutil_test.go" 时,它显示:

util\commonutil_test.go:8: undefined: GenerateUniqueID
FAIL    command-line-arguments [build failed]

将测试中的 GenerateUniqueID 改为 util.GenerateUniqueID 可以解决这个问题,但是当使用 Goconvey 运行覆盖率时会导致构建失败:

can't load package: import cycle not allowed
package rudygunawan.com/MyProject/HFLC-Go/util
    imports rudygunawan.com/MyProject/HFLC-Go/util

有什么解决这个问题的想法吗?我感到困惑。

Go 版本是 go1.7.1 windows/386。

英文:

Having issue creating unit test of one of my source file ( commonutil.go )

package util

import "github.com/nu7hatch/gouuid"

// GenerateUUID Returns generated UUID sequence
func GenerateUniqueID(hostname string) (string, error) {
	var result, err = uuid.NewV4()
	return hostname + ":" + result.String(), err
}

For the above source, I created the test file "commonutil_test.go" ( in the same package )

package util

import "testing" 
func TestCommonUtil(t *testing.T) {
t.Run("Test generate UUID", func(t *testing.T) {

	var uuid, _ = GenerateUniqueID ("test")
	//fmt.Printf("UUID isa %v \n", uuid)
	if uuid == "" {
		t.Errorf("UUID expected, but result is empty ")
	}
})

However when trying executing "go test util/commonutil_test.go" it shows :

> util\commonutil_test.go:8: undefined: GenerateUniqueID
FAIL command-line-arguments [build failed]

Changing to util.GenerateUniqueID in the test solve the problem, however when running coverage using Goconvey will cause build failure :

> can't load package: import cycle not allowed
package rudygunawan.com/MyProject/HFLC-Go/util
imports rudygunawan.com/MyProject/HFLC-Go/util

Any idea to solve this issue? I am confused.

Go version is go1.7.1 windows/386

答案1

得分: 1

刚刚意识到这是一个愚蠢的错误。测试的包应该是"util_test"。将测试放在单独的包中(但仍在同一个文件夹中)有助于解决导入循环问题,同时仍然可以解决未定义的错误。

英文:

Just realize it is a silly mistake. The package for the test should be "util_test". Putting the test in the separate package ( but still in the same folder) help solve import cycle issue, yet still allow to solve the undefined error.

答案2

得分: 1

我通常编写Go单元测试的方式是在与被测试代码相同的包中创建一个(或多个)..._test.go文件,每个广泛的测试集合都有一个Test...函数。

package util

import "testing"

func TestGenerateUniqueID(t *testing.T) {
   var uuid1, uuid2 string
   uuid1, err := GenerateUniqueID("test")
   if err != nil {
     t.Errorf("期望没有错误,得到的错误为 %s", err) // 也许使用 Fatalf?
   }
   if uuid1 == "" {
     t.Errorf("期望非空字符串,得到的是空字符串 (uuid1)")
   }
   uuid2, err := GenerateUniqueID("test")
   if err != nil {
     t.Errorf("期望没有错误,得到的错误为 %s", err) // 也许使用 Fatalf?
   }
   if uuid2 == "" {
     t.Errorf("期望非空字符串,得到的是空字符串 (uuid2)")
   }
   if uuid1 == uuid2 {
     t.Errorf("期望 uuid1 和 uuid2 不同,两者都是 %s", uuid1)
   }
}

我倾向于进行白盒测试的原因之一是,通常有一大堆非导出代码也应该进行测试。在这个具体的小例子中,对于白盒测试和黑盒测试来说,没有明显的优劣之分,因为所有可测试的功能都已经是导出的。

英文:

The way I normally write Go unit tests is to have one (or more) ..._test.go files, in the same package as the code being tested, with one Test... function for each broad set of tests to be done.

package util

import "testing

func TestGenerateUniqueID(t *testing.T) {
   var uuid1, uuid2 string
   uuid1, err = GenerateUniqueID("test")
   if err != nil {
     t.Errorf("Expected no error, got %s", err) // Maybe Fatalf?
   }
   if uuid1 == "" {
     t.Errorf("Expected non-empty string, got empty string (uuid1)")
   }
   uuid2, err = GenerateUniqueID("test")
   if err != nil {
     t.Errorf("Expected no error, got %s", err) // Maybe Fatalf?
   }
   if uuid2 == "" {
     t.Errorf("Expected non-empty string, got empty string (uuid2)")
   }
   if uuid1 == uuid2 {
     t.Errorf("Expected uuid1 and uuid2 to be different, both are %s", uuid1)
   }
}

One of the reasons I tend towards whitebox testing (where I can do "blackbox testing" by carefully not accessing package internals) is that there's usually a whole slew of non-exported code that really should be tested as well. In this specific, small, example, there's no massive argument for one over the other, since all the functionality that can be tested is already exported.

答案3

得分: 1

我遇到了一个类似的问题,当我尝试运行单个测试文件时。

我希望,由于这是一种测试驱动的开发方式,我只想运行当前正在开发的代码的测试,而不是运行所有的测试。

解决方案是不从文件中运行测试,而是通过名称(实际上是一个正则表达式)运行特定的测试。所以在你的情况下,我猜应该是这样的:

go test ./util -run TestCommonUtil

另一种方法似乎是列出构建测试代码所需的所有文件:

go test util/commonutil_test.go util/commonutil.go
英文:

I've run into a similar problem, when I was trying to run a single test file.

I wanted that, as it was a kind of test driven development thing, where I wanted to run tests only for the code I was working on at the moment, and not all the x-minutes running tests.

The solution turned out to be not running tests from a file, but rather running a specific test by name (actually a regex). So in your case I guess it would be:

go test ./util -run TestCommonUtil

An alternative seems to be listing all the files needed to build your test code:

go test util/commonutil_test.go util/commonutil.go

huangapple
  • 本文由 发表于 2016年9月28日 11:35:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/39737599.html
匿名

发表评论

匿名网友

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

确定