This is a creation in Article, where the information may have evolved or changed.
Golang unit test example
How do I write unit tests under Golang? The official testing package is a little shabby, but fortunately we have gocheck.
What is a good unit test?
Unit test golang and golang unit test best practices
Before entering the subject, first to review the previous summary of the unit test several principles:
http://www.atatech.org/articles/2523
Golang unit test
1 单元测试应该在最低的功能/参数上验证程序的正确性...3 单元测试过后,机器状态保持不变...6 独立性,单元测试的运行/通过/失败不依赖于别的测试,可以人为构造数据,以保持单元测试的独立性。
Good unit testing should follow the above principles; a good unit testing framework should facilitate our practice of these principles.
Unit testing in golang
Gocheck, easy to use
Gocheck Official website: http://labix.org/gocheck
Golang Official testing package is very weak: Incredibly even assert does not support. Gocheck in the testing library, enriched a lot of features, take us out of the Golang official testing framework under the endless "if...else ..." misery. Features that are especially useful include:
Unit test golang mock
Assert assertion + rich judgment verb: deep multi-type contrast, string comparison (even support regular match!) )。
Organize test cases by suite to support suite-level setup () and teardown ().
Create and delete temporary files/directories.
Example 1: Unit tests related to file operations
Golang unit test database
"After the unit test, the machine state remains the same" principle tells us that if the unit test to read and write files, the unit test to clean up the created temporary files.
Gocheck can create a temporary directory and automatically delete it at the end of the test, eliminating the manual cleanup steps.
Example:
package hello_testimport ( "testing" "io/ioutil" "io" . "gopkg.in/check.v1")const txt = "adfagaggafaf"// Hook up gocheck into the "go test" runner.func Test(t *testing.T) { TestingT(t) }type MySuite struct { dir string // 测试用的临时目录 f string // 测试用的临时文件}var _ = Suite(&MySuite{})// Setupsuite 准备测试用的临时文件func (s *MySuite) SetUpSuite(c *C) { dir := c.MkDir() // Suite结束后会自动销毁c.MkDir()创建的目录 tmpfile, err := ioutil.TempFile(dir, "") if err != nil { c.Errorf("Fail to create test file: %v\n", tmpfile.Name(), err) } err = WriteFile(tmpfile.Name(), txt) if err != nil { c.Errorf("Fail to prepare test file.%v\n", tmpfile.Name(), err) } s.dir = dir s.f = tmpfile.Name() }func (s *MySuite) TestFoo(c *C) { // ... 实际测试代码 c.Assert(bkpName, Matches, s.f+".ops_agent_bkp.+")}
Example 2:mock Web API-related unit tests
The principle of "independence" tells us that it is best to mock the data for functions that need to invoke the external API. Using Gocheck's Setupsuite () and Teardownsuite () methods, you can create a new HTTP test server and close it at the end.
Example:
Package Hello_testimport ("FMT" "Net/http" "Net/http/httptest" "testing". "GOPKG.IN/CHECK.V1") const (RESP1 = ' {"" data ": {" cluster ":" * * * * * "," hostname ":" xxxxx "}," Err_cod E ": 0," err_msg ":" "} ' Resp2 = ' {" Data ": [{" hostname ":" E18h13551.xxx "," IP ":" 100.22. 33.44 "," state ":" Good "}, {" hostname ":" dddd "," IP ":" 101.14.12.55 "," state ":" Good "}]," Err_code ": 0," err_msg ":" "} ')//Hook up Gocheck into the" Go Test "runner.func Test (t *test Ing. T) {testingt (t)}type mysuite struct {ts *httptest. Server}func (S *mysuite) Setupsuite (c *c) {h: = http. Newservemux () h.handlefunc ("/machine", func (w http). Responsewriter, R *http. Request) {fmt. Fprintln (W, RESP1)}) H.handlefunc ("/batch", func (w http). Responsewriter, R *http. Request) {fmt. Fprintln (W, RESP2)}) S.ts = Httptest. NewServer (h)}func (S *mysuite) Teardownsuite (c *c){S.ts.close ()}var _ = Suite (&mysuite{}) func (S *mysuite) Testfoo (c *c) {//Actual test code .... clustername, err: = G Etclustername (S.ts.url, "/machine") C.assert (Err, Isnil) C.assert (clustername, Equals, "minilvscluster-5e87-23842057 13506559 ")}
Other
Gocheck other useful features, such as a powerful checker. Can be flipped on the official website, making it easier to write unit tests.