monster.go
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.go
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("测试成功")
}
执行
go test -v