dpbl91234 2014-06-25 02:07
浏览 41

使用gocheck测试go(golang)代码,套件功能如何工作?

I was trying to use gocheck to test my go code. I was guiding myself with the following example (similar to the one provided by their website):

package hello_test

import (
    "testing"

    gocheck "gopkg.in/check.v1"
)

// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) {
    gocheck.TestingT(t)
}

type MySuite struct{} //<==== Does the struct have to be named that way, what if we have multiple of these and register them, is it a problem?

var _ = gocheck.Suite(&MySuite{}) // <==== What does this line do?

func (s *MySuite) TestHelloWorld(c *gocheck.C) {
    c.Assert(42, gocheck.Equals, "42")
    c.Check(42, gocheck.Equals, 42)
}

However, there are some lines I am not sure I understand even after reading the documentation. Why is the line type MySuite struct{} needed and even more of an interesting line, why is var _ = gocheck.Suite(&MySuite{}) needed? The first one, its easy to infer that one probably has to declare that struct first and create functions that will run the tests if implemented with the signature as shown. However, the second line beats me. I have literally no idea why its needed. The documentation says:

Suite registers the given value as a test suite to be run. Any methods starting with the Test prefix in the given value will be considered as a test method.

However, I am not sure about a lot of things. For instance, is there a problem if I run this function with multiple MySuite structs in the same file? Is there anything special about the type MySuite struct? Could the gocheck testing suite work even with some different struct being registered? Basically, how many times can we register a struct in one file and will it still work?

  • 写回答

1条回答 默认 最新

  • dsvyc66464 2014-06-25 02:47
    关注

    The gocheck.Suite function has the side effect of registering the given suite value with the gocheck package. Internally, it just adds the the suite to a slice of registered test suites. You could get the same effect with:

    func init() {
        gocheck.Suite(&MySuite{})
    }
    

    Either form should work, so it is just a matter of style.

    The tests in the registered test suites are run when you call gocheck.TestingT. You do this in your test called Test, which will be picked up by Go's testing framework. This is how gocheck tests are integrated into the testing framework. Note that you only need a single invocation of TestingT to run all test suites: not one for each test suite.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题