3

I'm using gomock (source mode) and wish to mock a piece of code that looks something like:

type foo interface {
  MethodA() int
}

type Boo interface {
  MethodB(f foo) string
}

where the unexported foo interface is used as an argument in MethodB(). After using mockgen, the mocked MethodB() looks like:

func (m &MockBoo) MethodB(f foo) string { ... }

which is erroneous because foo is unexported and can't be accessed.

Was wondering if theres a way around it (eg. for foo to be Mockfoo instead as the argument)?

PS. I tried gomock reflect mode as well but it had the same problem.

kito
  • 41
  • 7

1 Answers1

0

To test private types, declare your tests in the same package as the type. Doing so will allow you to access the private symbols.


Example

Test

package foo
import (
    "testing"

    "github.com/golang/mock/gomock"
)
func TestName(t *testing.T) {
    con := gomock.NewController(t)
    defer con.Finish()
    boo := NewMockBoo(con)
    var F foo
    boo.EXPECT().MethodB(F)
    if len(boo.MethodB(F)) > 0 {
        t.Fail()
    }
}

Generate mocks

$ mockgen -source=foo.go -package foo -destination foo_mock.go

foo.go

package foo


type foo interface {
  MethodA() int
}

type Boo interface {
  MethodB(f foo) string
}

Running the test:

$ go test  -v 
=== RUN   TestName
--- PASS: TestName (0.00s)
PASS
ok      foo 0.001s