注意事项:
_test.goperson_test.goTest开头person_test.goTestReStoret *testing.Tgo test -v person_test.go cal.gogo test -v -test.run TestReStore
go test -v
文件名:person.go
package model
import(
//"fmt"
"encoding/json"
"io/ioutil"
)
/*首字母小写,引入后不能直接使用*/
type Person struct{
Name string
Age int
Skill string
}
//序列化存储
func (this * Person)Store() bool {
data,err := json.Marshal(this)
if err != nil {
return false
}
filePath := "F:/Go/src/gocode/project_01/b.txt"
err = ioutil.WriteFile(filePath,data,0666)
if err != nil {
return false
}
return true
}
//读取反序列化内容
func (this * Person)ReStore()bool{
filePath := "F:/Go/src/gocode/project_01/b.txt"
data,err := ioutil.ReadFile(filePath)
if err != nil {
return false
}
err = json.Unmarshal(data,this)
if err != nil {
return false
}
return true
}
文件名:person_test.go
package model
import(
"testing"
)
func TestStore(t *testing.T){
person := &Person{
Name:"ywh",
Age:21,
Skill:"music",
}
res := person.Store()
if !res {
t.Fatalf("model.Store() 错误,希望为=%v 实际为=%v",true,res)
}
t.Logf("model.Store() 测试成功")
}
func TestReStore(t * testing.T){
var person = &Person{}
res := person.ReStore()
if !res {
t.Fatalf("model.ReStore() 错误,希望为=%v 实际为=%v",true,res)
}
if person.Name != "ywh"{
t.Fatalf("model.ReStore() 错误,希望为=%v 实际为=%v","ywh",person.Name)
}
t.Logf("model.ReStore() 测试成功")
}
输出:
=== RUN TestStore
person_test.go:19: model.Store() 测试成功
--- PASS: TestStore (0.00s)
=== RUN TestReStore
person_test.go:33: model.ReStore() 测试成功
--- PASS: TestReStore (0.00s)
PASS
ok gocode/project_01/model 0.023s