我正试图解决围棋中的空手道切术作为练习,并从我的测试用例中坚持这个编译器错误:
调用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
的任何参考。
源文件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 (*T) Fail
func (c *T) Fail()
Fail表示函数失败,但继续执行。
T.common.Fail()
没有参数
试试Errorf
:
例如,function (*T) error
func (c *T) Errorf(format string, args ...interface{})
Errorf相当于Logf后面跟着Fail。
this.Errorf("Failed asserting that %v is %v", actual, expected)