模拟接口函数未调用

时间:2018-10-12 05:28:04

标签: unit-testing go mocking testify

我正在尝试使用testify模拟库编写Go单元测试。我正在关注此博客http://goinbigdata.com/testing-go-code-with-testify/。我已经将模拟接口传递给了newCalculator函数,但是仍然调用Random接口的Random1而不是struct randomMock的Random1函数。

calculator.go

package calculator

type Random interface {
  Random1(limit int) int
}

func newCalculator(rnd Random) Random {
  return calc{
    rnd: rnd,
  }
}

type calc struct {
  rnd Random
}

func (c calc) Random1(limit int) int {
  return limit
}

calculator_test.go

package calculator

import (
  "github.com/stretchr/testify/assert"
  "github.com/stretchr/testify/mock"
  "testing"
)

type randomMock struct {
  mock.Mock
}

func (o randomMock) Random1(limit int) int {
  args := o.Called(limit)
  return args.Int(0)
}

func TestRandom(t *testing.T) {
  rnd := new(randomMock)
  rnd.On("Random1", 100).Return(7)
  calc := newCalculator(rnd)
  assert.Equal(t, 7, calc.Random1(100))
}

Output on running: go test
--- FAIL: TestRandom (0.00s)
calculator_test.go:22:
        Error Trace:    calculator_test.go:22
        Error:          Not equal:
                        expected: 7
                        actual  : 100
        Test:           TestRandom
FAIL
exit status 1

1 个答案:

答案 0 :(得分:2)

我自己弄的。我首先错过了对rnd结构的调用。

func (c calc) Random1(limit int) int {
  return c.rnd.Random1(limit)
}
相关问题