Skip to content

Generating mocks out of structs instead of interfaces. #1049

@arvenil

Description

@arvenil

One of patterns I see often is to create a structure with several methods, but then consumers use only slice of these methods via interfaces. E.g...

Repo

type UserRepo struct {
    db *sql.DB
}

func (*UserRepo) Get(id string) (User, error) 
func (*UserRepo) Create(user User) (User, error)
func (*UserRepo) Update(user User) (User, error)
func (*UserRepo) Delete(id string) error

Interface to get an user

type UserRepo interface{
    Get(id string) (User, error) 
}

Interface to delete a user

type UserRepo interface{
    Delete(id string) error
}

Interface to add a user

type UserRepo interface{
    Get(id string) (User, error)
    Update(user User) (User, error)
}

This leads to creating 3 mocks, under different packages, with different set of methods, but also sometimes some duplication between them. At first sight it seems like a good approach since mocks deliver exactly what is needed and nothing more, however the more the struct grows the more generating mocks becomes a burden as multiple packages use same structure and similar interfaces, yet we over and over generate mocks that have only subset of methods.

Ideally, I could generate one big mock based directly on the struct, and it would fulfill all interfaces with all kinds of combination of methods.

Is there a way for mockery to generate mocks based directly on structs?

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