Mocaccino
Mocaccino is a mocking framework for the Go programming language in the same
fashion as gomock. However, typed stubs is available, and chaining is supported.
This library is heavily inspired by the aforementioned project.
Installation
First, install mocagen
:
go install github.com/heyvito/mocaccino/mocagen@latest
Generating Stubs
The mocagen
utility is responsible for generating code based on either source
files, or external packages present in your go.mod
.
Providing Source Files
The simplest call to the codegen utility takes an output directory through
the -o
parameter, an input file, and a list of interfaces to have stubs
generated.
mocagen -o mocks ./my_interface.go MyInterface
Alternatively, when generating stubs from source files, mocagen
provides
a way to generate stubs for all interfaces present in the source file by
providing a single all
interface instead of a list:
mocagen -o mocks ./my_interface.go all
Providing External Packages
In order to generate stubs from external packages declared in your go.mod
,
simply provide the package name instead of a file path:
mocagen -o mocks github.com/someuser/somepackage InterfaceA InterfaceB
Available Arguments
--package NAME
: Package to be used when generating sources. If absent,
will be inferred from --out
--rename OLD=NEW[,OLD=NEW[,...]]
: Assigns new names to generated interfaces.
Renames OLD
to NEW
when generating stubs.
--out PATH
: Sets the path to the directory in which sources will be generated.
Directories will be created as required in case they don't exist. Required.
Using Stubs
gomock users will find the interface provided by Mocaccino quite familiar.
First, create a Controller
, then create a mock instance by calling the New
function associated with the name of a generated stub.
For instance:
// impl.go
package example
//go:generate mocagen -o . impl.go Service
type User struct {
Name string
Address string
}
type Message struct {
Subject string
Body string
}
type RandomService interface {
PerformAdd(a, b int) (int, error)
PerformSend(user *User, mail *Message) error
}
// impl_test.go
package example
import (
"github.com/heyvito/mocaccino"
"github.com/stretchr/testify/require"
"testing"
)
func TestSimpleCall(t *testing.T) {
ctrl := mocaccino.NewController(t)
mock := NewRandomServiceMock(ctrl)
mock.EXPECT().PerformAdd().With(1, 2).Return(3, nil)
result, err := mock.PerformAdd(1, 2)
require.NoError(t, err)
require.Equal(t, 3, result)
}