unit-testing - 使用testing.T作为匿名结构体字段: "too many arguments in call to this.T.common.Fail"

标签 unit-testing struct go

我正在尝试解决 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 (*T) Fail

func (c *T) Fail()

Fail marks the function as having failed but continues execution.

T.common.Fail() 没有参数。

尝试Errorf:

func (*T) 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/

相关文章:

C 指针 : what's the difference between struc* A, struct *A 和 struct * A?

go - 使用 GO 语言以 CSV 格式写入/保存数据

go - 在导入包时出现此错误知道如何解决这个问题吗?

go - 如何覆盖 DefaultHTTPErrorHandler 格式消息

python - 使用 patch to 模拟一个函数(而不是一个方法)

unit-testing - junit测试应使用main/resources

c++ - 结构问题(C++)

c - 为什么我可以分配结构但不能比较它们

c# - 如何断言集合只包含一个具有给定属性值的元素?

javascript - 使用子组件发出的 Jest : custom event handled by parent, 测试 Vue