zone := injection.GetGlobalConfigs().DefaultTimezone loc, err := time.LoadLocation(zone)
我必须测试一个内部调用这些方法的方法,我需要为该方法编写单元测试,用于错误情况,即时间。LoadLocation(zone)返回错误。是否有任何实现可以做到这些?期待建议
7vux5j2d1#
希望能成功
package main import ( "fmt" "testing" "time" ) type Temp struct { TimeLocation func(name string) (*time.Location, error) } func (t Temp) DoSomeThing() error { loc, err := t.TimeLocation("") if err != nil { return err } fmt.Println(loc) return nil } func Test_Temp(t *testing.T) { cases := []struct { name string locFunc func(name string) (*time.Location, error) wantErr bool }{ {"default", time.LoadLocation, false}, {"error", func(name string) (*time.Location, error) { return nil, fmt.Errorf("test error") }, true}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { temp := Temp{TimeLocation: c.locFunc} err := temp.DoSomeThing() if err != nil != c.wantErr { t.Fatalf("wantErr except %v, got %v", c.wantErr, err != nil) } }) } }
1条答案
按热度按时间7vux5j2d1#
希望能成功