moq icon indicating copy to clipboard operation
moq copied to clipboard

feat: support generic interface generation

Open cgorenflo opened this issue 3 years ago • 1 comments

Description

This addresses issue #173 regarding mock generation for interfaces with generic types. It works (almost) with the full scope of what is possible to define with golang 1.18. The test file shows the usage of interfaces with multiple type parameters, any constraints, constraints with embedded interface and basic type constraints, as well as aliasing of a generic interface.

Limitation:

An Interface with a generic type that has both a type constraint and additional interface functions defined cannot be generated accurately. In order to ensure the correct interface implementation, the mock needs to be cast to the interface with a specific type parameter. Example:

var _ GenericInterface[string] = GenericInterfaceMock[string]

Consider this type parameter:

type Constraint interface{
   ~int32 | string
   DoSomething() error
}

It is not even guaranteed that an implementation exists, so templating cannot simply pick one. These are the options to handle this case:

  1. Fail to generate such a constraint correctly
  2. Remove the check against the interface in this case
  3. Generate a mock for the Constraint interface

I don't think skipping the interface check without the user specifying it would be the right way to go and option 3 is a more involved implementation. This PR should cover the vast majority of use cases, so I chose to not implement this edge case for now and discuss it before going down that route.

cgorenflo avatar Apr 14 '22 14:04 cgorenflo

@matryer let me know how I can help to get this change merged!

cgorenflo avatar Apr 20 '22 03:04 cgorenflo

Not sure why the build did not run here but this broke support for Go versions older than 1.18. We should indicate the same when we release it @matryer

sudo-suhas avatar Nov 13 '22 05:11 sudo-suhas

Released in v0.3.0 🎉

sudo-suhas avatar Nov 20 '22 06:11 sudo-suhas