标签:testing run out code var info success bsp errors
future.go
package future type SuccessFunc func(string) type FailFunc func(error) type ExecuteStringFunc func() (string, error) type MaybeString struct { successFunc SuccessFunc failFunc FailFunc } func (s *MaybeString) Success(f SuccessFunc) *MaybeString { s.successFunc = f return s } func (s *MaybeString) Fail(f FailFunc) *MaybeString { s.failFunc = f return s } func (s *MaybeString) Execute(f ExecuteStringFunc) { go func(s *MaybeString) { str, err := f() if err != nil { s.failFunc(err) } else { s.successFunc(str) } }(s) }
future_test.go
package future import ( "errors" "sync" "testing" "time" ) func TestStringOrError_Execute(t *testing.T) { future := &MaybeString{} t.Run("Success result", func(t *testing.T) { var wg sync.WaitGroup wg.Add(1) go timeout(t, wg) future.Success(func(s string) { t.Log(s) wg.Done() }).Fail(func(e error) { t.Fail() wg.Done() }) future.Execute(func() (string, error) { return "Hello World!", nil }) wg.Wait() }) t.Run("Error result", func(t *testing.T) { var wg sync.WaitGroup wg.Add(1) future.Success(func(s string) { t.Fail() wg.Done() }).Fail(func(e error) { t.Log(e.Error()) wg.Done() }) future.Execute(func() (string, error) { return "", errors.New("Error ocurred") }) wg.Wait() }) } func timeout(t *testing.T, wg sync.WaitGroup) { time.Sleep(time.Second) t.Log("Timeout") t.Fail() wg.Done() }
标签:testing run out code var info success bsp errors
原文地址:https://www.cnblogs.com/aguncn/p/11921486.html