matryer / moq

Interface mocking tool for go generate

Home Page:http://bit.ly/meetmoq

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

import cycle if mocks generated outside of the tested package

umputun opened this issue · comments

Unless I'm doing something very wrong I don't see how this can work. In the generated code the first line needs import of my source package, i.e.

import (
	"sync"

	"example.com/pkg/requester/v2"
)

// Ensure, that RepeaterSvcMock does implement requester.RepeaterSvc.
// If this is not the case, regenerate this file with moq.
var _ requester.RepeaterSvc = &RepeaterSvcMock{}

And in my tests, I need to import this mock package, so I get import cycle not allowed in test.

Mock generated like this:

//go:generate moq -out mocks/repeater.go -pkg mocks -fmt goimports . RepeaterSvc

If I remove var _ requester.RepeaterSvc = &RepeaterSvcMock{} and import "example.com/pkg/requester/v2" everything works fine. Is it expected behavior and user suppose to alter generated files manually in this case?

Which package are you writing the test in? Have you considered using pkg_test as the package for writing the tests? I think that can avoid the import cycle issue.

Which package are you writing the test in?

Usually, I write tests in the package I'm testing.

Have you considered using pkg_test as the package for writing the tests? I think that can avoid the import cycle issue.

Sure it will, thx for the suggestion. But this is not really a universal solution, because in some cases I do need the test to be in the same package as the code.

To add a little bit of context: we are migrating mocks from mockery generated to moq in several large projects. In some cases testing code should access non-exported vars/fields/func of the package for various reasons. Some are valid, for example tests sets some enviroment, like fake time.Now function or we have to test non-exported functions. Either way, I don't want to change the testing logic in order to be able to use moq's generated mocks.

I think, excluding this initial assignment in the generated code, i.e. var _ requester.RepeaterSvc = &RepeaterSvcMock{} in my case, could be done automatically (optionally) as a part of moq generation logic. Maybe a new flag for this?

@umputun Hi! Why here's still no tag?

@umputun Hi! Why here's still no tag?

No idea, I'm not a maintainer.

Just needed this, how lucky I am it was already merged! Thanks guys!