有没有办法在golang中模拟time.loadLocation()以用于单元测试?

mftmpeh8  于 2023-04-18  发布在  Go
关注(0)|答案(1)|浏览(91)
zone := injection.GetGlobalConfigs().DefaultTimezone

loc, err := time.LoadLocation(zone)

我必须测试一个内部调用这些方法的方法,我需要为该方法编写单元测试,用于错误情况,即时间。LoadLocation(zone)返回错误。是否有任何实现可以做到这些?
期待建议

7vux5j2d

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)
            }
        })
    }
}

相关问题