Unit testing Golang:如何生成net/http超时错误以执行单元测试
我得到一段代码,如下所示:Unit testing Golang:如何生成net/http超时错误以执行单元测试,unit-testing,go,Unit Testing,Go,我得到一段代码,如下所示: 如果timeoutErr,则ok:=err.(净错误);确定(&timeoutErr.Timeout)(){ //一些需要测试的代码 } 如何生成与此处条件匹配的错误,以便代码通过if。错误是一个接口: type Error interface { error Timeout() bool // Is the error a timeout? Temporary() bool // Is the error tem
如果timeoutErr,则ok:=err.(净错误);确定(&timeoutErr.Timeout)(){
//一些需要测试的代码
}
如何生成与此处条件匹配的错误,以便代码通过if。
错误是一个接口:
type Error interface {
error
Timeout() bool // Is the error a timeout?
Temporary() bool // Is the error temporary?
}
要实现它,您需要执行以下操作(未测试):
请注意,您也必须实现Error()
,因为Error
嵌入了Error
只要实现就可以了?为什么不模拟返回正确值的方法来返回timeoutErr
?您能给我看一些实际的代码吗,我已经尝试了几种方法来实现错误接口,但是我一直遇到编译错误。我是刚来Golang的新手,所以单行指令对我来说有点难。我不知道我必须将error
放入我的MyError
结构中。谢谢你的回复,我的UT终于开始工作了。我想(e错误)
应该是(e错误)
。由于这是公认的答案,请更新它,以免混淆其他人。
type MyError struct {
error
}
func (e MyError) Timeout() bool {
return true
}
func (e MyError) Temporary() bool {
return true
}
func (e MyError) Error() string {
return ""
}