Go语言test之类方法测试

时间:2022-05-05
本文章向大家介绍Go语言test之类方法测试,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Go语言提供了完善的单元测试支持,开发人员可以方便的编写测试代码,保证自己代码的质量。在目前的例子中,一般看到都是普通函数的例子。下面我将举类方法的测试例子来展示一下Go语言的魅力。

首先是代码所在的文件xml.go:

package myxml import "fmt" import "encoding/xml" import "testing" func Test_XMLRsp_ToString(t *testing.T) { in := XMLRsp{xml.Name{Space: "", Local: "XMLRsp"}, "1", "1", "1"} out := []byte(xml.Header) out = append(out, []byte(`<XMLRsp><res_code>1</res_code><res_message>1</res_message><can_use>1</can_use></XMLRsp>`)...) r := in b, _ := r.ToString() if b != string(out) { t.Errorf("XMLRsp_ToString failed, result is: [%s]n", b) fmt.Printf("Expectation is: [%s]n", out) } else { fmt.Printf("XMLRsp_ToString result is: [%s]n", b) } } func Test_XMLRsp_Parse(t *testing.T) { in := []byte(`<XMLRsp><res_code>1</res_code><res_message>1</res_message><can_use>1</can_use></XMLRsp>`) out := XMLRsp{xml.Name{Space: "", Local: "XMLRsp"}, "1", "1", "1"} r := new(XMLRsp) _ = r.Parse(in) if *r != out { t.Errorf("XMLRsp_Parse failed, result is: [%s]n", *r) fmt.Printf("Expectation is: [%s]n", out) } else { fmt.Printf("XMLRsp_Parse result is: [%s]n", *r) } }

接着编写单元测试代码,注意单元测试代码应和被测试的代码在同一个包,且应使用xxx_test.go的规则来命名测试代码所在的文件,例如对上面的代码文件,应将测试文件命名为xml_test.go,包括以下的代码:

package myxml import "fmt" import "encoding/xml" import "testing" func Test_XMLRsp_ToString(t *testing.T) { in := XMLRsp{xml.Name{Space: "", Local: "XMLRsp"}, "1", "1", "1"} out := []byte(xml.Header) out = append(out, []byte(`<XMLRsp><res_code>1</res_code><res_message>1</res_message><can_use>1</can_use></XMLRsp>`)...) r := in b, _ := r.ToString() if b != string(out) { t.Errorf("XMLRsp_ToString failed, result is: [%s]n", b) fmt.Printf("Expectation is: [%s]n", out) } else { fmt.Printf("XMLRsp_ToString result is: [%s]n", b) } } func Test_XMLRsp_Parse(t *testing.T) { in := []byte(`<XMLRsp><res_code>1</res_code><res_message>1</res_message><can_use>1</can_use></XMLRsp>`) out := XMLRsp{xml.Name{Space: "", Local: "XMLRsp"}, "1", "1", "1"} r := new(XMLRsp) _ = r.Parse(in) if *r != out { t.Errorf("XMLRsp_Parse failed, result is: [%s]n", *r) fmt.Printf("Expectation is: [%s]n", out) } else { fmt.Printf("XMLRsp_Parse result is: [%s]n", *r) } }

测试代码中,函数可以用如下方式命名:Test_T_M,其中T为类型名,M为方法名,这样容易区分,但这不是Go语言的强制要求。

具体测试代码里先构造了一个类XMLRsp的对象,然后通过它去调用相应的类方法,本质上与其他单元测试代码并无不同。

上面测试代码第15行,先用了一个类型转换 string ( out ) 来得到一个string类型的out表示,因为Go语言里slice之间不能直接比较。

运行go test命令,可以得到类似如下的结果:

XMLRsp_ToString result is: [<?xml version="1.0" encoding="UTF-8"?><XMLRsp><res_code>1</res_code><res_message>1</res_message><can_use>1</can_use></XMLRsp>]
XMLRsp_Parse result is: [{{ XMLRsp} 1 1 1}]
PASS
ok      myxml    1.016s

表示这次测试的结果为PASS,大功告成,你可以忙着写其他的代码去了^-^