问题描述
我现在正在思考如何编写测试来检查给定的代码是否恐慌?我知道Go使用以避免恐慌,但不像说,Java代码,你不能真正指定什么代码应该跳过的情况下恐慌或你有什么。所以如果我有一个函数:
func f(t * testing.T){
defer func(){
如果r:= recover(); r!= nil {
fmt.Println(在f中恢复,r)
}
}()
OtherFunctionThatPanics()
t.Errorf(The代码没有恐慌)
}
我无法确定是否 OtherFunctionThatPanics
恐慌,我们恢复,或者如果该功能根本不恐慌。如果没有恐慌并且在恐慌时执行哪个代码,我该如何指定跳过哪些代码?如何检查我们是否发现了一些恐慌?
测试
并不真正具有成功的概念,只有失败。所以你上面的代码是正确的。您可能会发现这种风格稍微更清晰,但它基本上是一样的。
func TestPanic(t * testing.T){
推迟func(){
如果r:= recover(); r == nil {
t.Errorf(代码没有恐慌)
}
}()
//以下是测试中的代码
OtherFunctionThatPanics()
}
我通常会找到测试
相当弱。您可能对更强大的测试引擎感兴趣,例如。即使你不想要完整的银杏系统,你也可以使用它的匹配器库,,它可以与测试
。 Gomega包含如下匹配器:
Expect(OtherFunctionThatPanics).To(Panic())
您也可以将恐慌检查包括进一个简单的函数中:
func TestPanic(t * testing.T){
assertPanic(t,OtherFunctionThatPanics)
}
func assertPanic(t * testing.T,f func ()){
推迟func(){
如果r:= recover(); r == nil {
t.Errorf(The code did not panic)
}
}()
f()
}
I'm currently pondering how to write tests that check if a given piece of code panicked? I know that Go uses recover
to catch panics, but unlike say, Java code, you can't really specify what code should be skipped in case of a panic or what have you. So if I have a function:
func f(t *testing.T) {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered in f", r)
}
}()
OtherFunctionThatPanics()
t.Errorf("The code did not panic")
}
I can't really tell whether OtherFunctionThatPanics
panicked and we recovered, or if the function did not panic at all. How do I specify which code to skip over if there is no panic and which code to execute if there is a panic? How can I check whether there was some panic we recovered from?
testing
doesn't really have the concept of "success," only failure. So your code above is about right. You might find this style slightly more clear, but it's basically the same thing.
func TestPanic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
// The following is the code under test
OtherFunctionThatPanics()
}
I generally find testing
to be fairly weak. You may be interested in more powerful testing engines like Ginkgo. Even if you don't want the full Ginkgo system, you can use just its matcher library, Gomega, which can be used along with testing
. Gomega includes matchers like:
Expect(OtherFunctionThatPanics).To(Panic())
You can also wrap up panic-checking into a simple function:
func TestPanic(t *testing.T) {
assertPanic(t, OtherFunctionThatPanics)
}
func assertPanic(t *testing.T, f func()) {
defer func() {
if r := recover(); r == nil {
t.Errorf("The code did not panic")
}
}()
f()
}
这篇关于如何测试恐慌?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!