unit-testing - 戈朗 : how to generate a net/http timeout Error to perform unit test

标签 unit-testing go

我得到了一段如下代码:

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/

相关文章:

c++ - CPPUnit 中测试套件属性使用的示例是什么? (CPPUNIT_TEST_SUITE_PROPERTY)

c# - 在测试管理器中排序编码的 UI 测试和结果

amazon-web-services - 如何将 S3 数据加载到本地内存,而不是保存到文件

docker - Docker容器内的Kerberos客户端

go - 延迟执行关闭文件

date - 将日期从 DD-MON-YY 转换为 YYYYMMDD

java - 使用 Robolectric,如何在运行测试类中的所有测试方法之前和之后初始化和完成内容

python - 我想模拟打开一个现有的测试文件,对其应用一个函数进行测试,但不更改文件的实际内容

unit-testing - 如何让 Selenium 服务器与 htmlunit 一起工作?

c - 为什么在使用 libiconv 而不是 iconv 二进制文件时会得到不同的结果?