monster.gohtml
package monster import ( "encoding/json" "fmt" "io/ioutil" ) type Monster struct { Name string Age int Skill string } func (this *Monster) Store() bool { data, err := json.Marshal(this) if err != nil { fmt.Printf("marshal err = %v", err) return false } filePath := "d:/goProject/test/monster.log" err = ioutil.WriteFile(filePath, data, 0666) if err != nil { fmt.Printf("write file err = %v", err) return false } return true } func (this *Monster) ReStore() bool { filePath := "d:/goProject/test/monster.log" data, err := ioutil.ReadFile(filePath) if err != nil { fmt.Printf("read file err = %v", err) return false } err = json.Unmarshal(data, this) if err != nil { fmt.Printf("unmarshal err = %v", err) return false } return true }
monster_test.gojson
package monster import "testing" func TestMonster_Store(t *testing.T) { monster := &Monster{ Name: "紅孩兒", Age: 10, Skill: "吐火", } res := monster.Store() if !res { t.Fatalf("Monster.Store() 錯誤, 但願是%v 實際爲%v", true, res) } t.Logf("測試成功") } func TestMonster_ReStore(t *testing.T) { var monster = &Monster{} res := monster.ReStore() if !res { t.Fatalf("Monster.ReStore() 錯誤, 但願是%v 實際爲%v", true, res) } t.Logf("測試成功") }
執行 ide
go test -v