如何测试golang中的主要包函数? [英] How to test the main package functions in golang?

查看:245
本文介绍了如何测试golang中的主要包函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想测试一些包含在我的主包中的函数,但是我的测试似乎无法访问这些函数。



我的示例main.go文件如下所示:

  package main 

import(
log

$ b func main(){
log.Printf(foo())
}

func foo()string {
返回Foo
}

和我的main_test.go文件如下所示:

 包主

导入(
测试


func Foo(t testing.T){
t.Error(foo())
}

当我运行 go test main_test.go 我得到



<$ p $
.\main_test.go:8:undefined:foo
FAIL命令行参数[生成失败]

据我所知,即使我将测试文件移动到其他地方并尝试从main.go文件导入,我也无法导入因为它是 package main



构造这些测试的正确方法是什么?我是否应该从 main 包中删除所有内容,并将其作为一个简单的主函数来运行所有内容,然后在自己的包中测试这些函数,还是有办法让我调用这些函数函数从测试期间的主文件中获得

解决方案

在命令行中指定文件时,必须指定所有文件



这是我的跑步:

  $ ls 
main。 go main_test.go
$ go test * .go
ok命令行参数0.003s

请注意,在我的版本中,我在命令行上运行了main.go和main_test.go

另外,您的_test文件不太正确,您需要将您的测试函数称为TestXXX并接受一个指向测试的指针。

以下是修改的版本:

  package main 

import(
testing


func TestFoo(t * testing .T){
t.Error(foo())
}

和修改过的输出:

<$ p $ TestFoo(0.00s)
main_test.go:8:Foo
FAIL
FAIL命令 $ go test * .go
--- FAIL -line-arguments 0.003s


I want to test a few functions that are included in my main package, but my tests don't appear to be able to access those functions.

My sample main.go file looks like:

package main

import (
    "log"
)

func main() {
    log.Printf(foo())
}

func foo() string {
    return "Foo"
}

and my main_test.go file looks like:

package main

import (
    "testing"
)

func Foo(t testing.T) {
    t.Error(foo())
}

when I run go test main_test.go I get

# command-line-arguments
.\main_test.go:8: undefined: foo
FAIL    command-line-arguments [build failed]

As I understand, even if I moved the test file elsewhere and tried importing from the main.go file, I couldn't import it, since it's package main.

What is the correct way of structuring such tests? Should I just remove everything from the main package asides a simple main function to run everything and then test the functions in their own package, or is there a way for me to call those functions from the main file during testing?

解决方案

when you specify files on the command line, you have to specify all of them

Here's my run:

$ ls
main.go     main_test.go
$ go test *.go
ok      command-line-arguments  0.003s

note, in my version, I ran with both main.go and main_test.go on the command line

Also, your _test file is not quite right, you need your test function to be called TestXXX and take a pointer to testing.T

Here's the modified verison:

package main

import (
    "testing"
)

func TestFoo(t *testing.T) {
    t.Error(foo())
}

and the modified output:

$ go test *.go
--- FAIL: TestFoo (0.00s)
    main_test.go:8: Foo
FAIL
FAIL    command-line-arguments  0.003s

这篇关于如何测试golang中的主要包函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆