Amar Prakash Pandey
Amar Prakash Pandey

Reputation: 1336

Struct with an pointer to an Interface mock error

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.

Upvotes: 0

Views: 1651

Answers (2)

jiang
jiang

Reputation: 41

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

Upvotes: 3

nipuna
nipuna

Reputation: 4095

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}

Upvotes: 1

Related Questions