测试 net/http?

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

Testing net/http?

问题

我对如何构建Go Web应用程序及其测试有些困惑。我已经阅读了《如何编写Go代码》1,但仍然不太明白。例如,我有一个名为"beacon"的Go项目,在根目录下有一个beacon.go文件。添加一个简单的beacon_test.go文件(从http://golang.org/pkg/net/http/httptest/#example_Server中完全复制)会导致以下错误:

$ go test
# github.com/jelder/beacon
./beacon_test.go:11: main redeclared in this block
	previous declaration at ./beacon.go:216
FAIL	github.com/jelder/beacon [build failed]

确实,第11行是func main()。如果我将beacon_test.go中的package main改为package hello,则会出现以下错误:

can't load package: package github.com/jelder/beacon: found packages main (beacon.go) and hello (beacon_test.go) in /Users/jacob/src/github.com/jelder/beacon
英文:

I am a little confused about how to structure a go web app and its tests. I have read the How to Write Go Code but still don't get it. For example, I have a go project called "beacon" with a beacon.go file at the root. Adding a trivial beacon_test.go file (copied verbatim from http://golang.org/pkg/net/http/httptest/#example_Server) causes this error:

$ go test
# github.com/jelder/beacon
./beacon_test.go:11: main redeclared in this block
	previous declaration at ./beacon.go:216
FAIL	github.com/jelder/beacon [build failed]

Sure enough, line 11 is func main(). If I instead change the package main line in my beacon_test.go to package hello, I get this error instead:

can't load package: package github.com/jelder/beacon: found packages main (beacon.go) and hello (beacon_test.go) in /Users/jacob/src/github.com/jelder/beacon

答案1

得分: 1

beacon_test.go还有一个名为main()的函数,请将其重命名为TestFirst(或者任何其他以Test开头的名称,注意大写的T很重要)。这是没有必要的。只需从您正在工作的包内部(包含*.go文件的那个包)运行go test .即可。如果需要更多帮助,请发布完整的文件。

英文:

beacon_test.go has also a function called main() rename it to TestFirst (or any other name you like as long as it starts with Test, note the uppercase T is important). There is no need for that. Just run go test . from inside the package you are working on (the one containing the *.go files). Post the full files if you need more help.

huangapple
  • 本文由 发表于 2015年1月15日 07:53:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/27954631.html
匿名

发表评论

匿名网友

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

确定