Leon's Blogging

Coding blogging for hackers.

Golang - Mock

| Comments

Simple code use to test

string.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import "fmt"

type Stringer interface {
  Name(hi string) string
}

type human struct {
  name string
}

func (h *human) Name(hi string) string {
  say := fmt.Sprintf("%v %v", hi, h.name)
  return say
}

func main() {
  h := &human{name: "Leon"}
  fmt.Println(SayName(h))
}

func SayName(people Stringer) string {
  return people.Name("hi")
}

create mock data

default is .

1
mockery -name=Stringer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Code generated by mockery v1.0.0. DO NOT EDIT.

package mocks

import mock "github.com/stretchr/testify/mock"

// Stringer is an autogenerated mock type for the Stringer type
type Stringer struct {
  mock.Mock
}

// Name provides a mock function with given fields: hi
func (_m *Stringer) Name(hi string) string {
  ret := _m.Called(hi)

  var r0 string
  if rf, ok := ret.Get(0).(func(string) string); ok {
      r0 = rf(hi)
  } else {
      r0 = ret.Get(0).(string)
  }

  return r0
}

Write test with mock data

string_test.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package main

import (
  "testing"

  "github.com/mgleon08/mock/mocks"
  "github.com/stretchr/testify/assert"
  "github.com/stretchr/testify/mock"
)

func Test_SayName(t *testing.T) {
  // mock interface
  mockStringer := &mocks.Stringer{}
  // mock function and expected return you want data
  mockStringer.On("Name", mock.Anything).Return("hi, test")

  t.Run("test", func(t *testing.T) {
      assert.Equal(t, "hi, test", SayName(mockStringer))
  })
}

Reference:

Comments