momock

command module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 3, 2023 License: MIT Imports: 12 Imported by: 0

README

Momock

About

Generating Go mocks for testing.

Features / Roadmap
Feature Status
Creating mock file
Choosing mock file location
Choosing mock file package name
Choosing mock struct name
Assigning build tag 🔜
Choosing assertion framework
Matching statically typed arguments
Returning statically typed outputs
Matching multiple invocations
Erroring if expectations were set but not triggered 🔜
Erroring if expectations were not set but triggered

Usage

Place that generate directive at the top of file containing the interface you want to generate a mock for:

//go:generate go run github.com/panpito/momock

package playground

import (
	"context"
)

type SomeInterface interface {
	Do(ctx context.Context, x string) (context.Context, error)
}

Use native generate go command:

go generate ./...

It will generate a mock file (*_mock.go) alongside your interface file. Please do not modify it.

Let's say you have a service using the previous interface:

package playground

import "context"

type MyService struct {
	TheInterface SomeInterface
}

func (receiver MyService) UseInterface(ctx context.Context) error {
	_, err := receiver.TheInterface.Do(ctx, "hello")

	return err
}

Happy path:

func Test_Sucess(t *testing.T) {
	// given
	ctx := context.TODO()

	mock := playground.NewMockSomeInterface(t)
	mock.MockManager.SetExpectations([]momock.MockCall{
		{
			Method: mock.Do,
			In:     []any{ctx, "hello"},
			Out:    []any{nil, nil},
		},
	})

	myStruct := playground.MyService{
		TheInterface: mock,
	}

	// when
	result := myStruct.UseInterface(ctx)

	// then
	if result != nil {
		t.Fatalf("was expecting nil")
	}
}

Forgetting to setup the mock expectation, will generate that error:

=== RUN   Test_ForgotToSetExpectations
    manager.go:45: Was not expecting any mock calls

Not matching the arguments, will generate that error:

=== RUN   Test_WrongArgumentsToTheMock
    manager.go:70: 
        Argument: 	1
        Got: 		GOODBYE
        Wanted: 	hello

Providing the wrong number of arguments, will generate that error:

=== RUN   Test_WrongNumberOfArguments
    manager.go:57: Wrong number of inputs

Installation

At the root of the project, extend your tools.go file:

//go:build tools

package your_project

import (
	_ "github.com/panpito/momock"
)

And then go mod download.

Contributing

Please free to fork, create a branch and open a pull request.

License

This is under MIT license.

Contact

Please contact: Twitter

Documentation

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL