英文:
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")
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论