【问题标题】:How do I test Go's "testing" package functions?如何测试 Go 的“测试”包功能?
【发布时间】:2026-01-30 09:50:01
【问题描述】:

我正在编写一个测试实用程序函数库,我希望它们自己进行测试。

一个这样的函数的例子是:

func IsShwifty(t *testing.T, foo string) bool {
    result, err := bar.MyFunction(string)
    if err != nil {
      t.Error("Failed to get shwifty: " + foo, err)
    }
    return result == "shwifty"
}

我想写一个TestIsShwifty 来输入一些东西,让MyFunction 返回一个错误,然后让t.Error。然后,我想让TestIsShwifty 传递类似以下内容:

func TestIsShwifty(t *testing.T) {
  if doesError(t, IsShwifty(t)) == false {
    t.Error("Oh know! We didn't error!")
  }
}

这在 Go 中可能吗?

【问题讨论】:

  • 您遇到了哪些障碍?错误是什么?
  • 这个错误会破坏我的测试,但我希望我的测试在出错时通过。
  • 您似乎想要一些测试工具不支持的东西。我不认为你会实现它。

标签: unit-testing testing go


【解决方案1】:

我想通了!

我只需要创建一个单独的testing.T 实例。

func TestIsShwifty(t *testing.T) {
  newT := testing.T{}
  IsShwifty(newT)
  if newT.Failed() == false {
    t.Error("Test should have failed")
  }
}

【讨论】: