Fabian Schmengler
Fabian Schmengler

Reputation: 24551

Using testing.T as anonymous struct field: "too many arguments in call to this.T.common.Fail"

I am trying to solve the Karate Chop kata in Go as an exercise and stuck with this compiler error from my test case:

too many arguments in call to this.T.common.Fail

I wrapped testing.T into a struct with additional methods, as an anonymous struct field:

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}))
  ...
}

I expect this.Fail to call Fail() on the anonymous testing.T struct field, which takes a string parameter. Why isn't this the case and where does this.T.common.Fail come from? I cannot find any reference to common in the testing package documentation.

Upvotes: 2

Views: 296

Answers (1)

peterSO
peterSO

Reputation: 166559

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.

There are no arguments to T.common.Fail().

Try Errorf:

func (*T) Errorf

func (c *T) Errorf(format string, args ...interface{})

Errorf is equivalent to Logf followed by Fail.

For example,

this.Errorf("Failed asserting that %v is %v", actual, expected)

Upvotes: 3

Related Questions