我得到了一段如下代码:
if timeoutErr, ok := err.(net.Error); ok && timeoutErr.Timeout() {
// Some code that need to test
}
我怎样才能生成可以匹配此处条件的错误,以便代码通过 if。
最佳答案
Error
是一个接口(interface):
type Error interface {
error
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
}
要实现它,您需要执行以下操作(未经测试):
type MyError struct {
error
}
func (e MyError) Timeout() bool {
return true
}
func (e MyError) Temporary() bool {
return true
}
func (e MyError) Error() string {
return ""
}
请注意,您还必须实现 Error()
,因为 Error
嵌入了 error
。
关于unit-testing - 戈朗 : how to generate a net/http timeout Error to perform unit test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791349/