matryer / moq

Interface mocking tool for go generate
http://bit.ly/meetmoq
MIT License
2k stars 127 forks source link

import cycle if mocks generated outside of the tested package #139

Closed umputun closed 4 years ago

umputun commented 4 years ago

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?

sudo-suhas commented 4 years ago

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.

umputun commented 4 years ago

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?

spatecon commented 4 years ago

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

umputun commented 4 years ago

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

No idea, I'm not a maintainer.

matryer commented 4 years ago

@ilya310300 @umputun I did a release: https://github.com/matryer/moq/releases/tag/v0.1.4 Thanks

Streppel commented 3 years ago

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