Skip to content

Design Proposal: integration of github.com/matryer/moq-style mocks #712

@LandonTClipp

Description

@LandonTClipp

matryer/moq#208 was submitted to the maintainers of matryer/moq suggesting integrating the moq-style mocks into mockery. This suggestion seems well-received due to the benefits we could gain from combining the two projects' strengths.

This GitHub issue serves as a design proposal, discussion, and feature tracking page.

Background

vektra/mockery style of mocks rely on argument matching behavior provided from testify/mock. Expectations are created by mapping argument values to return values and side effects. Many valid criticisms have been raised about various pitfalls of this kind of expectation system. There are various alternate strategies for defining mock objects, and it's the goal of this project to combine the strengths of these alternate strategies with the strengths implemented in mockery itself.

mockery benefits

Speed

Mockery has undergone a huge rework over the last year with the new packages feature. Historically, mockery (and basically all other mock implementations) relied heavily on using go:generate statements to generate one mock per instantiation of mockery. This was extremely inefficient because it meant the packages.Load call required to parse the AST had to parse the package and all of its dependencies many times. This was an O(n*m) operation (where n is the number of mocks being generated, and m is the number of dependent packages). The rather trivial insight was to simply collect all packages to parse within a single list and pass all of them into packages.Load at once, which removed m from the equation. The new configuration model allows mockery to have this singular list of packages available within a single process.

Configuration inheritance

The other benefit of the configuration model is that allows inheritable configuration. Configuration can be specified at the top-level defaults, at the package level, and at the interface level, which parameters being inherited at each level. This is a powerful way to differentiate mock generation based on individual needs.

Templating

The configuration also takes advantage of Go templating, which allows users to call upon variables that are only known at runtime. Templating functions provide more power and flexibility to users to alter template variables.

mockery criticisms

  1. This type of mocking encourages increased coupling between tests due to the fact that it's easy to fall into a habit of asserting how the mock was called, which is bad practice (it asserts implementation details).
  2. Despite the great effort in adding type-safe expectation methods (Add mock generation with expecter #396), the necessity of specifying mock.Anything in mock objects means that the expecter's argument types have to be any. This means that argument types are not a compile-time safety guarantee but rather runtime.
  3. There is a huge amount of logic in testify that goes into correctly mapping method calls to their corresponding expectations. While testify does its job perfectly well, its clear that the complicated details of argument-matching necessitates a huge amount of logic to support it. A different mocking model could greatly simplify the generated code.

matryer/moq benefits

Simplicity

These style of mocks provide an incredibly simple way of defining mocks: you define the function to be run for your mock call. No argument matching, no assertions on how the mock was called. This simplicity encourages the programmer to not do too much with the mock, which reduces coupling. It doesn't make it impossible to do nasty things like call count and argument value assertions, but it makes it somewhat harder to do.

Type safety

moq objects are strictly type safe, which means test compilation will fail immediately if your mock doesn't satisfy the interface no matter what.

matryer/moq criticisms

Speed

Like all other mock projects besides mockery, moq relies on go:generate to instantiate one moq process per mock object. This is highly inefficient for the reasons aforementioned.

Configuration model

Its configuration model is entirely CLI parameter based. There are no config files, no inheritable config, no use of Go templating.

Proposal

Configuration syntax

moq-style mocks can be easily called upon in mockery by yaml such as this:

with-expecter: true
all: true
packages:
    github.com/my/repo:
        config: 
            style: moq
    github.com/my/other-repo:
        config: 
            style: mockery # this would be the default

Of course, style could be specified anywhere: at the top-level (defaults), in an environment var, in the CLI parameter, at the package level, or at the interface level.

Generated code

To maintain backwards compatibility with all existing usage of moq, the generated code would be identical to that of github.com/matryer/moq, minus any necessary differences to comments within the mock file. For those unfamiliar, this provides an example of the mock moq generates.

Given:

// Person represents a real person.
type Person struct {
	ID      string
	Name    string
	Company string
	Website string
}

// PersonStore provides access to Person objects.
type PersonStore interface {
	Get(ctx context.Context, id string) (*Person, error)
	Create(ctx context.Context, person *Person, confirm bool) error
}

This is generated.

type PersonStoreMock struct {
	// CreateFunc mocks the Create method.
	CreateFunc func(ctx context.Context, person *Person, confirm bool) error

	// GetFunc mocks the Get method.
	GetFunc func(ctx context.Context, id string) (*Person, error)
...

You then define each function individually in your test as such:

func TestSomethingThatUsesPersonStore(t *testing.T) {

    // make and configure a mocked PersonStore
    mockedPersonStore := &PersonStoreMock{
        CreateFunc: func(ctx context.Context, person *Person, confirm bool) error {
            panic("mock out the Create method")
        },
        GetFunc: func(ctx context.Context, id string) (*Person, error) {
            panic("mock out the Get method")
        },
    }

    // use mockedPersonStore in code that requires PersonStore
    // and then make assertions.

}

File placement

Where the mock files are physically placed will be according to the dir parameter, just as in the current system.

Code implementation

mockery has a concept of an Outputter, which is the object that determines where a mock should physically reside, and a Generator which creates the mock code. The Outputter should be modified to take an interface value in its constructor:

type CodeGenerator interface {
    io.WriterTo      // writes the generated mock to a writer (typically a file)
    Generate() error // generates the mock in-memory
}

Both mockery's current implementation, and moq, would implement this interface. The outputter will be provided the proper implementation here based off the style specified.

packages.Load changes

moq currently calls packages.Load based off filesystem path: https://github.com/matryer/moq/blob/c59089b2cd89d975f3d44924f04f37591fbd701d/internal/registry/registry.go#L31

This will need to be modified to integrate with the Interface struct that contains the AST information about each interface discovered in the package. This struct is generated using the information returned from here.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions