Golang:如何生成 net/http 超时错误来执行单元测试

Lê *_*Bảo 3 unit-testing go

我得到了一段如下代码:

if timeoutErr, ok := err.(net.Error); ok && timeoutErr.Timeout() {
    // Some code that need to test
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能生成一个与这里的条件匹配的错误,以便代码将流经 if.

Eli*_*sky 5

Error是一个接口:

type Error interface {
        error
        Timeout() bool   // Is the error a timeout?
        Temporary() bool // Is the error temporary?
}
Run Code Online (Sandbox Code Playgroud)

要实现它,您需要执行类似的操作(未经测试):

type MyError struct {
  error
}

func (e MyError) Timeout() bool {
  return true
}

func (e MyError) Temporary() bool {
  return true
}

func (e MyError) Error() string {
  return ""
}
Run Code Online (Sandbox Code Playgroud)

请注意,您也必须实现,Error()因为Errorembeds error