douganggu4392 2015-07-11 00:33
浏览 133

如何在golang中测试主要包功能?

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?

  • 写回答

4条回答 默认 最新

  • dream_high1026 2015-07-11 01:15
    关注

    Unit tests only go so far. At some point you have to actually run the program. Then you test that it works with real input, from real sources, producing real output to real destinations. For real.

    If you want to unit test a thing move it out of main().

    评论

报告相同问题?

悬赏问题

  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计