Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Satisfy unexported methods on interface in different package #489

Open
1 task done
lukestoward opened this issue Jul 1, 2022 · 1 comment
Open
1 task done

Satisfy unexported methods on interface in different package #489

lukestoward opened this issue Jul 1, 2022 · 1 comment

Comments

@lukestoward
Copy link

lukestoward commented Jul 1, 2022

I recently encountered an issue when trying to use mockery to generate a mock for an interface in package x that contains an unexported method.

// x/x.go

package x

type Foo interface {
	Bar()
	baz()
}

Generating a mock for this interface using

mockery --with-expecter --exported --dir x --name Foo --output mocks  
// y/y.go

package y

func example(t x.Foo) {
	t.Bar()
}
// y/y_test.go

func Test_example(t *testing.T) {
	foo := mocks.NewFoo(t)
	example(foo) // <-- error "cannot use foo (variable of type *mocks.Foo) as x.Foo value in argument to example: *mocks.Foo does not implement x.Foo (missing method baz)"
}

This is a limitation of in how we define a type to satisfy the interface. According to this post, if the type embeds the target interface, it satisfies the compiler. For example:

// Code generated by mockery v2.14.0. DO NOT EDIT.

package mocks

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

// Foo is an autogenerated mock type for the Foo type
type Foo struct {
	x.Foo // <-- manually adding this fixes the issue.
	mock.Mock
}

Therefore, my question is, would it be possible to embed the original interface in the mock if the interface has unexported methods?

Mockery Version

v2.14.0.

Golang Version

go 1.18.3

Installation Method

  • go install
@FLAGLORD
Copy link

You can embed the original interface to ensure mocked struct implements it.But you can not override it with mocked function. Because it is not exported, the mthod of the same name in the mock file is not the same as that method in the interface

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants