GoMock is a mocking framework for the Go programming language.

Overview

gomock Build Status GoDoc

GoMock is a mocking framework for the Go programming language. It integrates well with Go's built-in testing package, but can be used in other contexts too.

Installation

Once you have installed Go, install the mockgen tool.

To get the latest released version use:

GO111MODULE=on go get github.com/golang/mock/[email protected]

If you use mockgen in your CI pipeline, it may be more appropriate to fixate on a specific mockgen version.

Documentation

After installing, you can use go doc to get documentation:

go doc github.com/golang/mock/gomock

Alternatively, there is an online reference for the package hosted on GoPkgDoc here.

Running mockgen

mockgen has two modes of operation: source and reflect.

Source mode

Source mode generates mock interfaces from a source file. It is enabled by using the -source flag. Other flags that may be useful in this mode are -imports and -aux_files.

Example:

mockgen -source=foo.go [other options]

Reflect mode

Reflect mode generates mock interfaces by building a program that uses reflection to understand interfaces. It is enabled by passing two non-flag arguments: an import path, and a comma-separated list of symbols.

You can use "." to refer to the current path's package.

Example:

mockgen database/sql/driver Conn,Driver

# Convenient for `go:generate`.
mockgen . Conn,Driver

Flags

The mockgen command is used to generate source code for a mock class given a Go source file containing interfaces to be mocked. It supports the following flags:

  • -source: A file containing interfaces to be mocked.

  • -destination: A file to which to write the resulting source code. If you don't set this, the code is printed to standard output.

  • -package: The package to use for the resulting mock class source code. If you don't set this, the package name is mock_ concatenated with the package of the input file.

  • -imports: A list of explicit imports that should be used in the resulting source code, specified as a comma-separated list of elements of the form foo=bar/baz, where bar/baz is the package being imported and foo is the identifier to use for the package in the generated source code.

  • -aux_files: A list of additional files that should be consulted to resolve e.g. embedded interfaces defined in a different file. This is specified as a comma-separated list of elements of the form foo=bar/baz.go, where bar/baz.go is the source file and foo is the package name of that file used by the -source file.

  • -build_flags: (reflect mode only) Flags passed verbatim to go build.

  • -mock_names: A list of custom names for generated mocks. This is specified as a comma-separated list of elements of the form Repository=MockSensorRepository,Endpoint=MockSensorEndpoint, where Repository is the interface name and MockSensorRepository is the desired mock name (mock factory method and mock recorder will be named after the mock). If one of the interfaces has no custom name specified, then default naming convention will be used.

  • -self_package: The full package import path for the generated code. The purpose of this flag is to prevent import cycles in the generated code by trying to include its own package. This can happen if the mock's package is set to one of its inputs (usually the main one) and the output is stdio so mockgen cannot detect the final output package. Setting this flag will then tell mockgen which import to exclude.

  • -copyright_file: Copyright file used to add copyright header to the resulting source code.

For an example of the use of mockgen, see the sample/ directory. In simple cases, you will need only the -source flag.

Building Mocks

type Foo interface {
  Bar(x int) int
}

func SUT(f Foo) {
 // ...
}
func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)

  // Assert that Bar() is invoked.
  defer ctrl.Finish()

  m := NewMockFoo(ctrl)

  // Asserts that the first and only call to Bar() is passed 99.
  // Anything else will fail.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    Return(101)

  SUT(m)
}

If you are using a Go version of 1.14+, a mockgen version of 1.5.0+, and are passing a *testing.T into gomock.NewController(t) you no longer need to call ctrl.Finish() explicitly. It will be called for you automatically from a self registered Cleanup function.

Building Stubs

type Foo interface {
  Bar(x int) int
}

func SUT(f Foo) {
 // ...
}
func TestFoo(t *testing.T) {
  ctrl := gomock.NewController(t)
  defer ctrl.Finish()

  m := NewMockFoo(ctrl)

  // Does not make any assertions. Executes the anonymous functions and returns
  // its result when Bar is invoked with 99.
  m.
    EXPECT().
    Bar(gomock.Eq(99)).
    DoAndReturn(func(_ int) int {
      time.Sleep(1*time.Second)
      return 101
    }).
    AnyTimes()

  // Does not make any assertions. Returns 103 when Bar is invoked with 101.
  m.
    EXPECT().
    Bar(gomock.Eq(101)).
    Return(103).
    AnyTimes()

  SUT(m)
}

Modifying Failure Messages

When a matcher reports a failure, it prints the received (Got) vs the expected (Want) value.

Got: [3]
Want: is equal to 2
Expected call at user_test.go:33 doesn't match the argument at index 1.
Got: [0 1 1 2 3]
Want: is equal to 1
Modifying Want

The Want value comes from the matcher's String() method. If the matcher's default output doesn't meet your needs, then it can be modified as follows:

gomock.WantFormatter(
  gomock.StringerFunc(func() string { return "is equal to fifteen" }),
  gomock.Eq(15),
)

This modifies the gomock.Eq(15) matcher's output for Want: from is equal to 15 to is equal to fifteen.

Modifying Got

The Got value comes from the object's String() method if it is available. In some cases the output of an object is difficult to read (e.g., []byte) and it would be helpful for the test to print it differently. The following modifies how the Got value is formatted:

gomock.GotFormatterAdapter(
  gomock.GotFormatterFunc(func(i interface{}) string {
    // Leading 0s
    return fmt.Sprintf("%02d", i)
  }),
  gomock.Eq(15),
)

If the received value is 3, then it will be printed as 03.

Issues
  • Mockgen: Support generating mock for interfaces with generics

    Mockgen: Support generating mock for interfaces with generics

    Requested feature

    Mockgen should support generating mocks for interfaces with generics.

    Why the feature is needed The Go 1.18 is planned to be released soon, and I noticed that the mockgen tool doesn't support the generic. When a type parameter is in the interface, mockgen will throw an error.

    Code example: https://go.dev/play/p/g1G2OvZPQpT?v=gotip

    > go run github.com/golang/mock/mockgen -source=generic_mock.go
    2022/02/13 10:59:41 Loading input failed: don't know how to mock method of type *ast.IndexExpr
    exit status 1
    

    (Optional) Proposed solution

    1. In the code example above, the StudentRepository interface is concrete, so the gererated mock should be concrete too with the type parameters substituted.
    2. The BaseRepository interface is abstract, so the generated mock struct should also have the same type parameters.

    (My use case only needs 1, which mockery supports as of today.)

    type: feature request 
    opened by lingyv-li 43
  • support mocking vendored dependencies

    support mocking vendored dependencies

    • Generate temporary program in current directory tree to pick up vendored dependencies during build
    • Clean up the return of PkgPath according to the advice of rsc here https://github.com/golang/go/issues/12019#issuecomment-148747953

    This fixes #4

    The files I used to manually test this are here: https://gist.github.com/rgarcia/cf553169c4832543a0a9

    opened by rgarcia 33
  • mock does not import the source file

    mock does not import the source file

    I'm trying to generate a mock from a source.

    $ cat x.go
    package test
    
    type X struct{}
    
    type S interface {
    	F(X)
    }
    
    $ mockgen -source x.go
    // Automatically generated by MockGen. DO NOT EDIT!
    // Source: x.go
    
    package mock_test
    
    import (
    	gomock "github.com/golang/mock/gomock"
    )
    
    // Mock of S interface
    type MockS struct {
    	ctrl     *gomock.Controller
    	recorder *_MockSRecorder
    }
    
    // Recorder for MockS (not exported)
    type _MockSRecorder struct {
    	mock *MockS
    }
    
    func NewMockS(ctrl *gomock.Controller) *MockS {
    	mock := &MockS{ctrl: ctrl}
    	mock.recorder = &_MockSRecorder{mock}
    	return mock
    }
    
    func (_m *MockS) EXPECT() *_MockSRecorder {
    	return _m.recorder
    }
    
    func (_m *MockS) F(_param0 X) {
    	_m.ctrl.Call(_m, "F", _param0)
    }
    
    func (_mr *_MockSRecorder) F(arg0 interface{}) *gomock.Call {
    	return _mr.mock.ctrl.RecordCall(_mr.mock, "F", arg0)
    }
    

    The generated mock does not import the original source for the type X. Should I edit the generated mock? I tried some flags like -imports, but it didn't work.

    Thanks,

    opened by junghoahnsc 32
  • mockgen source mode does not work with go1.11 modules

    mockgen source mode does not work with go1.11 modules

    "self" import is generates as x ".". It works in gopath and with reflection based mockgen. Using -self_package does not affect the output.

    Sample program (foo.go):

    package foo
    
    type Arg struct {}
    
    type Foo interface {
    	Bar(a Arg) error
    }
    

    Used command: $ mockgen -source=foo.go

    Generated output:

    // Code generated by MockGen. DO NOT EDIT.
    // Source: foo.go
    
    // Package mock_foo is a generated GoMock package.
    package mock_foo
    
    import (
    	x "."
    	gomock "github.com/golang/mock/gomock"
    	reflect "reflect"
    )
    
    // MockFoo is a mock of Foo interface
    type MockFoo struct {
    	ctrl     *gomock.Controller
    	recorder *MockFooMockRecorder
    }
    
    // MockFooMockRecorder is the mock recorder for MockFoo
    type MockFooMockRecorder struct {
    	mock *MockFoo
    }
    
    // NewMockFoo creates a new mock instance
    func NewMockFoo(ctrl *gomock.Controller) *MockFoo {
    	mock := &MockFoo{ctrl: ctrl}
    	mock.recorder = &MockFooMockRecorder{mock}
    	return mock
    }
    
    // EXPECT returns an object that allows the caller to indicate expected use
    func (m *MockFoo) EXPECT() *MockFooMockRecorder {
    	return m.recorder
    }
    
    // Bar mocks base method
    func (m *MockFoo) Bar(a x.Arg) error {
    	ret := m.ctrl.Call(m, "Bar", a)
    	ret0, _ := ret[0].(error)
    	return ret0
    }
    
    // Bar indicates an expected call of Bar
    func (mr *MockFooMockRecorder) Bar(a interface{}) *gomock.Call {
    	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Bar", reflect.TypeOf((*MockFoo)(nil).Bar), a)
    }
    

    Versions: go version go1.11.2 darwin/amd64 mockgen latest version

    type: bug 
    opened by arjantop 31
  • return value depend on input value

    return value depend on input value

    Is there way do return value depend on the input? I want to do something like the following pseudo-code var response string mock.EXPECT().SomeMethod(gomock.Any()).AnyTimes().Do(func(input string) { response = input + input }).Return(response)

    I got deep into the code, and it look like it unsupported, I there other way to do it?

    opened by rantibi 29
  • mockgen stopped working after upgrading to Golang 1.13

    mockgen stopped working after upgrading to Golang 1.13

    We run gomock/mockgen inside of a docker container. Previously that docker container was based on golang 1.12, but we upgrade it to 1.13 today. After upgrading to golang 1.13, mockgen started failing out:

    mockgen --package=mock_seeds --destination=/go/src/github.com/xxx/yyy/mock_seeds/mock_seeds.go github.com/xxx/yyy/seeds ExternalAPIClient,ExternalAPIServer                                        
    go: github.com/xxx/[email protected]: invalid version: git fetch -f https://github.com/xxx/zzz refs/heads/*:refs/heads/* refs/tags/*:refs/tags/* in /go/pkg/mod/cache/vcs/595ef178a 519bba79a7580920dc80e819bacb31e39f9842a1de283c683f92cd1: exit status 128:
         fatal: could not read Username for 'https://github.com': terminal prompts disabled
    

    Our project has several golang modules it depends on that are private, with the obfuscated https://github.com/xxx/zzz being one of them. We use go mod vendor to commit them to the repo.

    Why is mockgen running go get or git fetch or anything like that?

    mockgen shouldn't be getting my source files, when they are all right there already.

    What is going on, and how to solve it?

    type: question status: needs more info modules 
    opened by veqryn 22
  • Avoid using packages.Load

    Avoid using packages.Load

    Description Partially fixing #419

    It turn out there are two places calling go list:

    This PR avoids calling packages.Load and saves one of the go list calls. Some performance data:

    With 0b87a54da2167cf3446363bb4b00c6de7677ceaa:

    $ go clean --cache --modcache && time go run ./mockgen -source /Users/zplin/gocode/src/github.com/bazelbuild/bazel-gazelle/language/lang.go > /dev/null
    go: downloading golang.org/x/tools v0.0.0-20190425150028-36563e24a262
    go: extracting golang.org/x/tools v0.0.0-20190425150028-36563e24a262
    go: finding golang.org/x/tools v0.0.0-20190425150028-36563e24a262
    go run ./mockgen -source  > /dev/null  6.98s user 6.10s system 121% cpu 10.767 total
    

    After this PR:

    $ go clean --cache --modcache && time go run ./mockgen -source /Users/zplin/gocode/src/github.com/bazelbuild/bazel-gazelle/language/lang.go > /dev/null
    go: downloading golang.org/x/mod v0.2.0
    go: extracting golang.org/x/mod v0.2.0
    go: downloading golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898
    go: extracting golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898
    go: finding golang.org/x/mod v0.2.0
    go: finding golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898
    go run ./mockgen -source  > /dev/null  3.77s user 3.81s system 118% cpu 6.383 total
    

    Submitter Checklist

    These are the criteria that every PR should meet, please check them off as you review them:

    • [ ] Includes tests

    Reviewer Notes

    • [ ] The code flow looks good.
    • [ ] Tests added.
    opened by linzhp 19
  • mockgen: Source mode compiles package

    mockgen: Source mode compiles package

    When using -source=interface.go the package that interface.go belongs to gets compiled/parsed before the mock is generated.

    This is a problem if the tests that uses this mock also resides in the same package, as NewMockInterface won't exists.

    This used to work on older versions.

    type: bug status: backlog 
    opened by HeinOldewageRetro 19
  • [Feature Request] Ability to check whether the expectations are met and reset mock expectations

    [Feature Request] Ability to check whether the expectations are met and reset mock expectations

    Requested feature:

    • Ability to check whether all expectations are met Currently, We only have EXPECT() which we can use in the user code and the rest (i.e. checking whether all expected calls were made) happens inside the controller. I would like to propose a utility which allows user code to check whether all expectations are met or not. A feature similar to the one which go-sqlmock provides, namely ExpectationsWereMet
    • Resetting the mock behavior so that any previous behavior in not propagated to other tests Currently, We need to redefine the controller to define the new mock behavior. I would like to propose a utility which allows user code to reset all previous expectations so that test separation is maintained and dirty state of other tests is not propagated to other tests.

    Why the feature is needed Right now, In my current project, While doing component-level testing, I need to inject the mocked dependencies of other services when my component gets initialized. So the controller is also defined there only. All these dependencies gets called in the code. It's time and resource consuming to initialize the application on each and every test. So if the above features are added then it would really help.

    The following is the high-level code structure on how I'm planning on consuming these features

    For the sake of brevity I've included only high-level part.

    file: ct_main_test.go // This defines the TestMain.go and initializes the application
    
    var remoteService
    
    func TestMain(m *testing.M) {
        // initialize application
        ctrl := controller.NewController(helper)
        remoteService = mock.MockedRemote(ctrl)
        service = initializeMyService(remoteService)    
        .
        .
        os.Exit(m.Run())
    }
    
    file: ct_some_file_test.go
    
    func Test_xxx(t *testing.T) {
          // Before proceeding, Reset any previous expectations
          remoteservice.ResetExpectations()
    
          // Given
          remoteService.Expect().ServiceMethod().Times(2)
    
         // When an API is called
         myService.SayHello()
    
         // Then
         remoteService.ExpectationsWereMet()    // Assert that all expectations were met. If expectations were not met, we throw an error
    }
    

    This would really help in implementing best practices in my current project and will help in avoid passing the dirty state between tests mistakenly.

    PS: Excuse me if it's possible somehow using the current features provided by gomock. In that case, Let me know how can I achieve the same. Thanks!

    status: needs discussion type: feature request 
    opened by hardikmodha 17
  • mockgen: handle more cases of

    mockgen: handle more cases of "duplicate" imports

    Description

    This partially addresses two issues related to how the source-mode parser handles embedded interfaces from other packages. Each is addressed in their own commit, but I've submitted this as a single PR since it is modifying very similar code. The problems this addresses are:

    Incorrect generation caused by packages with the same name

    When an interface embeds other interfaces that happen to refer to packages with the same name, we would previously generate incorrect mocks. For example, given following code:

    // source
    import (
        "some.org/package/foo"
        "some.org/package/bar"
    )
    
    type Source interface {
        foo.Foo
        bar.Bar
    }
    
    // some.org/package/foo
    package foo
    
    import "some.org/package/foo/internal/bar"
    
    type Foreign interface {
        bar.InternalBar
    }
    
    // some.org/package/bar
    
    type Bar interface {
        TopLevelBarMethod() string
    }
    
    // some.org/package/foo/internal/bar
    
    type Bar interface {
        InternalBarMethod() string
    }
    

    the resulting mock would have two generated implementations of TopLevelBarMethod() and no copies of InternalBarMethod(). This was because all interfaces were merged into a single map keyed by the package name.

    We solve this by creating a tree of fileParser objects rather than merging all imports and interfaces into a single set of maps. This helps ensure that transitive imports from the source file's dependencies don't erroneously conflict with any top-level imports.

    Fatal Error on duplicate imports

    Previously, it was possible to get the following error:

    2020/02/24 10:22:25 imported package collision: "log" imported twice
    

    From a multi-file package that happens to import two packages named "log." While the package itself is valid, the parser can't currently handle this case because it merges all imports into a single map. Fully fixing this issue will likely require larger changes. Here, we cover what I think will be many of the common cases of hitting this error by deferring the error until the ambiguous package name is actually referenced. This is enough to handle the following common case which currently results in this error:

    package service
    
    import "google.golang.org/grpc"
    
    type Test interface {
            grpc.ClientStream
    }
    

    Partially fixes #156 _

    Submitter Checklist

    These are the criteria that every PR should meet, please check them off as you review them:

    • [x] Includes tests: I've added a new integration-style test in mockgen/internal/tests/import_embedded_interface/

    Reviewer Notes

    • [ ] The code flow looks good.
    • [ ] Tests added.

    Release Notes

    - Improved handling of embedded interfaces in source-mode parser.
    
    opened by stevendanna 16
  • deduplicate methods to allow overlapping methods on embedded interfaces

    deduplicate methods to allow overlapping methods on embedded interfaces

    Fixes #497.

    Description

    This PR deduplicates methods to allow overlapping methods on embedded interfaces (which are valid Go since version 1.14). We're using the fact that if the name of the method matches, the parameters need to match as well (e.g. you can't combine two interfaces that both define a method sayHello(), where one signature is function sayHello() and the other one is function sayHello() error).

    Regarding the implementation: I did consider using a map (map[method name]*method) for deduplication, however, this would lead to a non-deterministic order when iterating over this map. I'm therefore deduplicating every time a new method is added to the interface. Clearly, the scaling behavior of this is not ideal for interfaces with a lot of methods. I could use an additional set to keep track of function names, but I figured that most interfaces will have a lot less than 20 or so methods, so the performance difference should be negligible. lmk if you disagree with my choice here.

    Submitter Checklist

    These are the criteria that every PR should meet, please check them off as you review them:

    • [x] Includes tests

    Reviewer Notes

    • [ ] The code flow looks good.
    • [x] Tests added.

    Release Notes

    deduplicate methods to allow overlapping methods on embedded interfaces

    - Deduplicate methods in order to allow overlapping methods when using embedded interfaces
    
    opened by marten-seemann 15
  • Introduce possibility to list required interfaces so mockgen won't generate all of them in source mode

    Introduce possibility to list required interfaces so mockgen won't generate all of them in source mode

    Requested feature Optional -interfaces flag for source mode so it will be possible to list only those interfaces that needed to be mocked.

    Why the feature is needed Using reflect mode it is possible to list only required interfaces. For example, if there is a file with 3 different interfaces and the developer wants to generate mocks only for 2 of them it is not possible with go:generate annotation:

    //go:generate mockgen -destination foo_mock.go -package myPackage -source file.go Foo
    type Foo interface {}
    //go:generate mockgen -destination bar_mock.go -package myPackage -source file.go Bar
    type Bar interface {}
    type Baz interface {}
    

    Such an approach won't work cause there will be two generated files in the same package with the same content which includes all 3 interfaces. There also will be conflicts between these two files.

    //go:generate mockgen -destination foo_mock.go -package myPackage -source file.go Foo, Bar
    type Foo interface {}
    type Bar interface {}
    type Baz interface {}
    

    The example above won't work also, there will be all 3 interface mocks in the generated file. (Optional) Proposed solution Introduce flag -interfaces which accepts a list of required interfaces separated by a comma. It will work like this:

    //go:generate mockgen -destination foo_mock.go -package myPackage -source file.go -interfaces Foo
    type Foo interface {}
    //go:generate mockgen -destination bar_mock.go -package myPackage -source file.go -interfaces Bar
    type Bar interface {}
    type Baz interface {}
    

    As a result, 2 files will be generated each containing a separate interface, Foo in foo_mock.go and Bar in bar_mock.go respectively. Also if we need Foo and Bar in a single generated file that will work also like this:

    //go:generate mockgen -destination foo_mock.go -package myPackage -source file.go -interfaces Foo, Bar
    type Foo interface {}
    type Bar interface {}
    type Baz interface {}
    
    type: feature request 
    opened by kliukovkin 0
  • add interfaces flag

    add interfaces flag

    This is a proposal for -interfaces flag using source mode. Using this flag it is possible to list only required interfaces to be mocked in source mode. Currently, source mode mocks all interfaces which -source file contains.

    Fixes https://github.com/golang/mock/issues/660

    opened by kliukovkin 1
  • Incorrectly treating generic types as exported types

    Incorrectly treating generic types as exported types

    Consider a source file notifier.go we want to mock, with the following pattern :

    type Clonable[T any] interface {
    	Clone() T
    }
    
    type Finder[T Clonable[T]] interface {
    	Find(ctx context.Context) ([]T, error)
    }
    
    type UpdateNotifier[T any] interface {
    
    	NotifyC(ctx context.Context) <-chan []T
    
    	Refresh(ctx context.Context)
    }
    

    Actual behavior A clear and concise description of what the bug is.

    The three following functions are generated

    // MockFinder is a mock of Finder interface.
    type MockFinder[T notifier.Clonable[notifier.T]] struct {
    	ctrl     *gomock.Controller
    	recorder *MockFinderMockRecorder[T]
    }
    
    // MockFinderMockRecorder is the mock recorder for MockFinder.
    type MockFinderMockRecorder[T notifier.Clonable[notifier.T]] struct {
    	mock *MockFinder[T]
    }
    
    // NewMockFinder creates a new mock instance.
    func NewMockFinder[T notifier.Clonable[notifier.T]](ctrl *gomock.Controller) *MockFinder[T] {
    	mock := &MockFinder[T]{ctrl: ctrl}
    	mock.recorder = &MockFinderMockRecorder[T]{mock}
    	return mock
    }
    

    Note that in the above the generic type T is treated as an exported type from notifier


    Expected behavior A clear and concise description of what you expected to happen.

    notifier.Clonable[notifier.T] should be notifier.Clonable[T] in the function signatures

    // MockFinder is a mock of Finder interface.
    type MockFinder[T notifier.Clonable[T]] struct {
    	/* ... */
    }
    
    // MockFinderMockRecorder is the mock recorder for MockFinder.
    type MockFinderMockRecorder[T notifier.Clonable[T]] struct {
    	/* ... */
    }
    
    // NewMockFinder creates a new mock instance.
    func NewMockFinder[T notifier.Clonable[T]](ctrl *gomock.Controller) *MockFinder[T] {
    	/* ... */
    }
    

    To Reproduce Steps to reproduce the behavior

    1. mockgen -source notifier.go -output notifier_mock.go

    Additional Information

    • gomock mode (reflect or source): source
    • gomock version or git ref: github.com/golang/mock v1.6.1-0.20220512030613-73266f9366fc
    • golang version: go version go1.18.2 darwin/arm64

    Triage Notes for the Maintainers

    Seems like a fun one

    opened by alexandreLamarre 1
  • Check arguments of callback function

    Check arguments of callback function

    Requested feature Check type of arguments and return type for callback function in Do/DoAndReturn while add callback, similar to check types of return values in Return function.

    Why the feature is needed Now Do/DoAndReturn functions check count arguments only, but real type checked at call moment. It will be better cause error on mock initialization instead of mock call - because I see line where initialization failed.

    (Optional) Proposed solution Check callback arguments in Do and DoAndReturn about it same as original func arg type of assignable from them.

    type: feature request 
    opened by rekby 0
  • Add call.Optional()

    Add call.Optional()

    Issue described in #655

    Changes

    • Add optional property to Call
    • Add Optional() to Call

    Example Test

    // Will not throw "aborting test due to missing call(s)"
    func TestOptional(t *testing.T) {
    	ctrl := gomock.NewController(t)
    	defer ctrl.Finish()
    
    	mockIndex := NewMockIndex(ctrl)
    
    	mockIndex.EXPECT().Get(gomock.Any()).Optional()
    }
    

    Thanks for any time spent reviewing this PR ❤️ .

    opened by MatthiasReumann 0
  • Make calls optional

    Make calls optional

    Requested feature call.Optional(), so that a expected function has not to be called.

    Why the feature is needed Currently, it is not possible to write universal mocks for all my tests since aborting test due to missing call(s) is thrown. Usually this would not be necessary or even advisable, however, in this particular case it would work just fine and reduces code duplication manifold.

    In the following (slimed down) example I create a mock DAO object, which I want to re-use in all different kind of tests. Unfortunately, I can't use it for all tests, since not all Calls are expected.

    func GetVideoSectionMock(t *testing.T) dao.VideoSectionDao {
    	sectionMock := mock_dao.NewMockVideoSectionDao(gomock.NewController(t))
    	sectionMock.EXPECT().Get(id).Return(section, nil)
    	sectionMock.EXPECT().Create(section).Return(nil)
    	return sectionMock
    }
    ...
    func TestSections(t *testing.T) {
          mock := GetVideoSectionMock(t)
          res := onlyCallGet(mock) // onlyCallGet calls sectionMock.Get(...) but not sectionMock.Create(...)
          assert.Equals(section, res)
    }
    

    What I've tried is setting minTimes to zero, but that unfortunately also doesn't work.

    If there is already a way to circumvent this problem let me know, thanks ❤️ .

    type: feature request 
    opened by MatthiasReumann 0
Releases(v1.6.0)
Owner
Go
The Go Programming Language
Go
Full-featured test framework for Go! Assertions, mocking, input testing, output capturing, and much more! 🍕

testza ?? Testza is like pizza for Go - you could life without it, but why should you? Get The Module | Documentation | Contributing | Code of Conduct

Marvin Wendt 389 Jun 18, 2022
Go Interface Mocking Tool

Charlatan Percolate's Go Interface Mocking Tool. Please read our introductory blog post. Installation go get github.com/percolate/charlatan Usage c

Percolate 195 May 23, 2022
HTTP traffic mocking and testing made easy in Go ༼ʘ̚ل͜ʘ̚༽

gock Versatile HTTP mocking made easy in Go that works with any net/http based stdlib implementation. Heavily inspired by nock. There is also its Pyth

Tom 1.6k Jun 24, 2022
HTTP mocking for Golang

httpmock Easy mocking of http responses from external resources. Install Currently supports Go 1.7 - 1.15. v1 branch has to be used instead of master.

Jared Morse 1.4k Jun 23, 2022
HTTP mocking to test API services for chaos scenarios

GAOS HTTP mocking to test API services for chaos scenarios Gaos, can create and provide custom mock restful services via using your fully-customizable

Trendyol Open Source 209 May 24, 2022
Lightweight HTTP mocking in Go (aka golang)

httpmock This library builds on Go's built-in httptest library, adding a more mockable interface that can be used easily with other mocking tools like

null 77 Jun 27, 2022
A simple and expressive HTTP server mocking library for end-to-end tests in Go.

mockhttp A simple and expressive HTTP server mocking library for end-to-end tests in Go. Installation go get -d github.com/americanas-go/mockhttp Exa

Americanas Go 6 Dec 19, 2021
Interface mocking tool for go generate

Interface mocking tool for go generate. What is Moq? Moq is a tool that generates a struct from any interface. The struct can be used in test code as

Mat Ryer 1.3k Jun 20, 2022
A Comprehensive Coverage Testing System for The Go Programming Language

goc 中文页 | goc is a comprehensive coverage testing system for The Go Programming Language, especially for some complex scenarios, like system testing c

Qiniu Cloud 531 Jun 17, 2022
Hamcrest matchers for the Go programming language

Note: This has not been maintained and/or updated since 2011. Perhaps consider corbym/gocrest, instead. Introduction Hamcrest is a fluent framework fo

null 27 Oct 12, 2021
Powerful mock generation tool for Go programming language

Summary Minimock generates mocks out of Go interface declarations. The main features of minimock are: It generates statically typed mocks and helpers.

Juno Inc. 455 Jun 15, 2022
Package cdp provides type-safe bindings for the Chrome DevTools Protocol (CDP), written in the Go programming language.

cdp Package cdp provides type-safe bindings for the Chrome DevTools Protocol (CDP), written in the Go programming language. The bindings are generated

Mathias Fredriksson 614 Jun 22, 2022
Coverage testing tool for The Go Programming Language

gocov Coverage reporting tool for The Go Programming Language Installation go get github.com/axw/gocov/gocov Usage There are currently four gocov comm

Andrew Wilkins 767 Jun 17, 2022
A Master list of Go Programming Tutorials, their write-ups, their source code and their current build status!

TutorialEdge TutorialEdge.net Go Tutorials ??‍?? ??‍?? Welcome to the TutorialEdge Go Repository! The goal of this repo is to be able to keep track of

TutorialEdge 274 Jun 15, 2022
Assert to perform programming assertions

Cli EN README Assert para realizar las aserciones de programación. GoDoc godoc for github Menú Principal Se configura un menú con ese ejemplo como dis

null 0 Jan 13, 2022
Rich testing for the Go language

Instructions Install the package with: go get gopkg.in/check.v1 Import it with: import "gopkg.in/check.v1" and use check as the package name inside

null 658 Jun 18, 2022
End to end functional test and automation framework

Declarative end to end functional testing (endly) This library is compatible with Go 1.12+ Please refer to CHANGELOG.md if you encounter breaking chan

Viant, Inc 209 Jun 26, 2022
Golang HTTP client testing framework

flute Golang HTTP client testing framework Presentation https://speakerdeck.com/szksh/flute-golang-http-client-testing-framework Overview flute is the

Shunsuke Suzuki 17 Apr 19, 2022
API testing framework inspired by frisby-js

frisby REST API testing framework inspired by frisby-js, written in Go Proposals I'm starting to work on frisby again with the following ideas: Read s

_Hofstadter 272 Jun 13, 2022