【问题标题】:Mock Interface function not getting called模拟接口函数没有被调用
【发布时间】:2018-10-12 05:28:03
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: unit-testing go mocking testify


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-17
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 2016-03-31
      • 2023-03-17
      • 1970-01-01
      • 2022-08-23
      • 1970-01-01
      相关资源
      最近更新 更多