使用测试。T 作为匿名结构字段:"too many arguments in call to this.T.common.Fail"



我正试图解决围棋中的空手道切术作为练习,并从我的测试用例中坚持这个编译器错误:

调用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)

最新更新