如何测试Go语言中的”testing”包函数?

huangapple go评论74阅读模式
英文:

How do I test Go's "testing" package functions?

问题

我正在编写一个测试实用函数的库,我希望能对它们进行自我测试。

以下是一个这样的函数示例:

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 no! We didn't error!")
    }
}

在Go语言中是否可以实现这个目标?

英文:

I'm writing a library of testing utility functions and I would like them to be themselves tested.

An example of one such function is:

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"
}

I would like to write a TestIsShwifty that feeds in something to make MyFunction return an error and then make t.Error. Then, I want to have the TestIsShwifty pass with something like:

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

Is this possible in Go?

答案1

得分: 1

我明白了!

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

func TestIsShwifty(t *testing.T) {
  newT := testing.T{}
  IsShwifty(newT)
  if newT.Failed() == false {
    t.Error("测试应该失败")
  }
}
英文:

I figured it out!

I just needed to create a separate instance of testing.T.

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

huangapple
  • 本文由 发表于 2017年2月8日 12:00:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/42104451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定