我正在尝试解决 Karate Chop Go 中的 kata 作为练习,并在我的测试用例中遇到了这个编译器错误:
too many arguments in call to this.T.common.Fail
我将 testing.T
包装到带有附加方法的结构中,作为匿名结构字段:
package main
import (
"fmt"
"testing"
)
type assertions struct {
*testing.T
}
func (this assertions) assert_equal(expected int, actual int) {
if (expected != actual) {
this.Fail(fmt.Sprintf("Failed asserting that %v is %v", actual, expected));
}
}
func TestChop(t *testing.T) {
test := assertions{t}
test.assert_equal(-1, Chop(3, []int{}))
test.assert_equal(-1, Chop(3, []int{1}))
...
}
我希望 this.Fail
在匿名 testing.T
结构字段上调用 Fail()
,该字段采用字符串参数。为什么情况并非如此? this.T.common.Fail
从何而来?我在 testing
包文档中找不到任何对 common
的引用。
最佳答案
Source file src/testing/testing.go
// Fail marks the function as having failed but continues execution. func (c *common) Fail() { c.mu.Lock() defer c.mu.Unlock() c.failed = true } // common holds the elements common between T and B and // captures common methods such as Errorf. type common struct { mu sync.RWMutex // guards output and failed output []byte // Output generated by test or benchmark. failed bool // Test or benchmark has failed. skipped bool // Test of benchmark has been skipped. finished bool start time.Time // Time test or benchmark started duration time.Duration self interface{} // To be sent on signal channel when done. signal chan interface{} // Output for serial tests. } // T is a type passed to Test functions to manage test state and support formatted test logs. // Logs are accumulated during execution and dumped to standard error when done. type T struct { common name string // Name of test. startParallel chan bool // Parallel tests will wait on this. }
func (c *T) Fail()
Fail marks the function as having failed but continues execution.
T.common.Fail()
没有参数。
尝试Errorf
:
func (c *T) Errorf(format string, args ...interface{})
Errorf is equivalent to Logf followed by Fail.
例如,
this.Errorf("Failed asserting that %v is %v", actual, expected)
关于unit-testing - 使用testing.T作为匿名结构体字段: "too many arguments in call to this.T.common.Fail",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172132/