Home > Mobile >  Struct with an pointer to an Interface mock error
Struct with an pointer to an Interface mock error

Time:12-23

package main

import (
    "github.com/golang/mock/gomock"
    "testing"
)

type Talker interface {
    talk() string
}

type Person struct {
    moth *Talker
}

func (p *Person) speak() string {
    return (*p.moth).talk()
}

func TestPerson(t *testing.T) {
    ctrl := gomock.NewController(t)
    mockTalker := NewMockTalker(ctl)

    person := Person{moth: mockTalker}
}

Assuming that I have already created a mock for Talker interface using mockgen.

I am getting error when I am creating Person{moth: mockTalker}. I am not able to pass mockTalker.

CodePudding user response:

Don't user pointer interface. Essentially interface is pointer

type Person struct {
    moth Talker
}

Normally, if function want return interface, it's will return new struct by pointer.

import "fmt"

type I interface {
    M()
}

type S struct {
}

func (s *S) M() {
    fmt.Println("M")
}

func NewI() I {
    return &S{}
}

func main() {
    i := NewI()
    i.M()
}
 

CodePudding user response:

In your Person struct the moth field is *Talker type. It is a pointer type of Talker interface. NewMockTalker(ctl) returns Talker type mock implementation.

You can do two things to fix this.

  1. Change the Person's moth field's type to Talker.
type Person struct {
    moth Talker
}

or

  1. pass pointer reference of mockTalker to the person initialization`
person := Person{moth: &mockTalker}
  • Related