Powerful mock generation tool for Go programming language

logo GoDoc Build Status Go Report Card Coverage Status Release Awesome

Summary

Minimock generates mocks out of Go interface declarations.

The main features of minimock are:

  • It generates statically typed mocks and helpers. There's no need for type assertions when you use minimock.
  • It's fully integrated with the standard Go "testing" package.
  • It's ready for Go modules.
  • It works well with table driven tests because you can set up mocks for several methods in one line of code using the builder pattern.
  • It can generate several mocks in one run.
  • It generates code that passes gometalinter checks.
  • It puts //go:generate instruction into the generated code, so all you need to do when the source interface is updated is to run the go generate ./... command from within the project's directory.
  • It provides Finish and Wait helpers to check if all mocked methods have been called during the test and keeps your test code clean and up to date.
  • It provides When and Then helpers to set up several expectations and results for any method.
  • It generates concurrent-safe mocks and mock invocation counters that you can use to manage mock behavior depending on the number of calls.
  • It can be used with the GoUnit tool which generates table-driven tests that make use of minimock.

Installation

If you use go modules please download the latest binary or install minimock from source:

go install github.com/gojuno/minimock/v3/cmd/minimock

If you don't use go modules please find the latest v2.x binary here or install minimock using v2 branch

Usage

 minimock [-i source.interface] [-o output/dir/or/file.go] [-g]
  -g	don't put go:generate instruction into the generated code
  -h	show this help message
  -i string
    	comma-separated names of the interfaces to mock, i.e fmt.Stringer,io.Reader
    	use io.* notation to generate mocks for all interfaces in the "io" package (default "*")
  -o string
    	comma-separated destination file names or packages to put the generated mocks in,
    	by default the generated mock is placed in the source package directory
  -s string
    	mock file suffix (default "_mock_test.go")

Let's say we have the following interface declaration in github.com/gojuno/minimock/tests package:

type Formatter interface {
	Format(string, ...interface{}) string
}

This will generate mocks for all interfaces defined in the "tests" package:

$ cd ~/go/src/github.com/gojuno/minimock/tests
$ minimock 

Here is how to generate a mock for the "Formatter" interface only:

$ cd ~/go/src/github.com/gojuno/minimock/tests
$ minimock -i Formatter 

Same using the relative package notation:

$ minimock -i ./tests.Formatter

Same using the full import path of the source package:

$ minimock -i github.com/gojuno/minimock/tests.Formatter -o ./tests/

All the examples above generate ./tests/formatter_mock_test.go file

Now it's time to use the generated mock. There are several ways it can be done.

Setting up a mock using the builder pattern and Expect/Return methods:

mc := minimock.NewController(t)
formatterMock := NewFormatterMock(mc).FormatMock.Expect("hello %s!", "world").Return("hello world!")

The builder pattern is convenient when you have more than one method to mock. Let's say we have an io.ReadCloser interface which has two methods: Read and Close

type ReadCloser interface {
	Read(p []byte) (n int, err error)
	Close() error
}

We can set up a mock using a simple one-liner:

mc := minimock.NewController(t)
readCloserMock := NewReadCloserMock(mc).ReadMock.Expect([]byte(1,2,3)).Return(3, nil).CloseMock.Return(nil)

But what if we don't want to check all arguments of the read method? Let's say we just want to check that the second element of the given slice "p" is 2. This is where "Inspect" helper comes into play:

mc := minimock.NewController(t)
readCloserMock := NewReadCloserMock(mc).ReadMock.Inspect(func(p []byte){
  assert.Equal(mc, 2, p[1])
}).Return(3, nil).CloseMock.Return(nil)

Setting up a mock using When/Then helpers:

mc := minimock.NewController(t)
formatterMock := NewFormatterMock(mc)
formatterMock.When("Hello %s!", "world").Then("Hello world!")
formatterMock.When("Hi %s!", "there").Then("Hi there!")

alternatively you can use the one-liner:

formatterMock = NewFormatterMock(mc).When("Hello %s!", "world").Then("Hello world!").When("Hi %s!", "there").Then("Hi there!")

Setting up a mock using the Set method:

mc := minimock.NewController(t)
formatterMock := NewFormatterMock(mc).FormatMock.Set(func(string, ...interface{}) string {
  return "minimock"
})

You can also use invocation counters in your mocks and tests:

mc := minimock.NewController(t)
formatterMock := NewFormatterMock(mc)
formatterMock.FormatMock.Set(func(string, ...interface{}) string {
  return fmt.Sprintf("minimock: %d", formatterMock.BeforeFormatCounter())
})

Make sure that your mocks are being used

Often we write tons of mocks to test our code but sometimes the tested code stops using mocked dependencies. You can easily identify this problem by using mc.Finish or mc.Wait helpers. These helpers ensure that all your mocks and expectations have been used at least once during the test run.

func TestSomething(t *testing.T) {
  mc := minimock.NewController(t)
  defer mc.Finish() //it will mark this example test as failed because there are no calls to formatterMock.Format() and readCloserMock.Read() below

  formatterMock := NewFormatterMock(mc)
  formatterMock.FormatMock.Return("minimock")

  readCloserMock := NewReadCloserMock(mc)
  readCloserMock.ReadMock.Return(5, nil)
}

Testing concurrent code

Testing concurrent code is tough. Fortunately minimock.Controller provides you with the helper method that makes testing concurrent code easy. Here is how it works:

func TestSomething(t *testing.T) {
  mc := minimock.NewController(t)

  //Wait ensures that all mocked methods have been called within the given time span
  //if any of the mocked methods have not been called Wait marks the test as failed
  defer mc.Wait(time.Second)

  formatterMock := NewFormatterMock(mc)
  formatterMock.FormatMock.Return("minimock")

  //tested code can run the mocked method in a goroutine
  go formatterMock.Format("hello world!")
}

Using GoUnit with minimock

Writing test is not only mocking the dependencies. Often the test itself contains a lot of boilerplate code. You can generate test stubs using GoUnit tool which has a nice template that uses minimock.

Happy mocking!

Owner
Juno Inc.
Juno is a fresh approach to ride sharing
Juno Inc.
Comments
  • Add flag to specify build tags

    Add flag to specify build tags

    I use minimock for my project and really like it. In that project, I have a lot of mocks. I want to move these mocks to separate package and exclude from the build for production. Hence, I need an ability to specify build tags during generating mocks.

  • "atomic redeclared as imported package name" build error

    Hi, great tool:), but is not working with interfaces with .../atomic types like "go.uber.org/atomic".

    For example for interface:

    import "go.uber.org/atomic"
    
    type At interface {
    	Method(*atomic.Int64)
    }
    
    

    minimock generates mock:

    package tt
    
    // DO NOT EDIT!
    // The code below was generated with http://github.com/gojuno/minimock (dev)
    
    //go:generate minimock -i github.com/BrightLocal/tt.At -o ./at_mock_test.go
    
    import (
    	"sync/atomic"
    	"time"
    
    	"go.uber.org/atomic"
    
    	"github.com/gojuno/minimock"
    )
    ...
    

    which produce build error:

    /at_mock_test.go:12:2: atomic redeclared as imported package name
    	previous declaration at ./at_mock_test.go:9:2
    
  • Implement a way to skip checking expectations for a mock object

    Implement a way to skip checking expectations for a mock object

    Based on #35.

    It would be great if a mock could be skipped when the mock controller checks to see if expectations were met. This has several use cases:

    • Argument values are not known at runtime (e.g. random)
    • Argument value is complex (e.g. struct with private fields)
    • Mocking an interface to either make a no-op implementation or to capture call args (satisfies both the above points and reduces boilerplate)

    Some possible naming schemes:

    FooMock.ExpectAnything().Return("val")
    FooMock.SkipExpectations()
    FooMock.CaptureOnly()
    

    ExpectAnything implies that the mock will be called at least once. SkipExpectations is the least vague IMO. CaptureOnly makes it sound like a Return() wouldn't work which probably isn't the desired functionality.

  • Data race in generated code

    Data race in generated code

    Hello guys, I probably have race in generated _mock file. This is my test https://pastebin.com/Bt5XAxhb go test ./ledger/light/proc/set_result_test.go -race -count 10000 full output here https://pastebin.com/EVUPkiVs short output:

    ==================
    WARNING: DATA RACE
    Write at 0x00c0004581a0 by goroutine 7:
      sync/atomic.AddInt64()
          /usr/local/Cellar/go/1.13/libexec/src/runtime/race_amd64.s:276 +0xb
      github.com/insolar/insolar/insolar/bus.(*SenderMock).Reply()
          /Users/radist/go/src/github.com/insolar/insolar/insolar/bus/sender_mock.go:179 +0xbed
      github.com/insolar/insolar/ledger/light/proc.(*SetResult).Proceed()
          /Users/radist/go/src/github.com/insolar/insolar/ledger/light/proc/set_result.go:152 +0xef9
      command-line-arguments_test.TestSetResult_Proceed_ResultDuplicated()
          /Users/radist/go/src/github.com/insolar/insolar/ledger/light/proc/set_result_test.go:263 +0xe68
      testing.tRunner()
          /usr/local/Cellar/go/1.13/libexec/src/testing/testing.go:909 +0x199
     
    Previous write at 0x00c0004581a0 by goroutine 18:
      command-line-arguments_test.TestSetResult_Proceed_HasOpenedOutgoing_Error.func3()
          /Users/radist/go/src/github.com/insolar/insolar/ledger/light/proc/set_result_test.go:696 +0x263
      github.com/insolar/insolar/ledger/light/executor.(*FilamentCalculatorMock).OpenedRequests()
          /Users/radist/go/src/github.com/insolar/insolar/ledger/light/executor/filament_calculator_mock.go:224 +0xe9b
      github.com/insolar/insolar/ledger/light/proc.(*SetResult).Proceed()
          /Users/radist/go/src/github.com/insolar/insolar/ledger/light/proc/set_result.go:157 +0x11be
      command-line-arguments_test.TestSetResult_Proceed_HasOpenedOutgoing_Error()
          /Users/radist/go/src/github.com/insolar/insolar/ledger/light/proc/set_result_test.go:715 +0x18ff
      testing.tRunner()
          /usr/local/Cellar/go/1.13/libexec/src/testing/testing.go:909 +0x199
    

    What I did? I've noticed that if I'm using Inspect instead of Set there is no race. So I added lock/unlock in mocked method before "Setted" func is calling and it helps

    // Reply implements Sender
    func (mmReply *SenderMock) Reply(ctx context.Context, origin payload.Meta, reply *message.Message) {
    	mm_atomic.AddUint64(&mmReply.beforeReplyCounter, 1)
    	defer mm_atomic.AddUint64(&mmReply.afterReplyCounter, 1)
    
    	if mmReply.inspectFuncReply != nil {
    		mmReply.inspectFuncReply(ctx, origin, reply)
    	}
    
    	params := &SenderMockReplyParams{ctx, origin, reply}
    
    	// Record call args
    	mmReply.ReplyMock.mutex.Lock()
    	mmReply.ReplyMock.callArgs = append(mmReply.ReplyMock.callArgs, params)
    	mmReply.ReplyMock.mutex.Unlock()
    
    	for _, e := range mmReply.ReplyMock.expectations {
    		if minimock.Equal(e.params, params) {
    			mm_atomic.AddUint64(&e.Counter, 1)
    			return
    		}
    	}
    
    	if mmReply.ReplyMock.defaultExpectation != nil {
    		mm_atomic.AddUint64(&mmReply.ReplyMock.defaultExpectation.Counter, 1)
    		want := mmReply.ReplyMock.defaultExpectation.params
    		got := SenderMockReplyParams{ctx, origin, reply}
    		if want != nil && !minimock.Equal(*want, got) {
    			mmReply.t.Errorf("SenderMock.Reply got unexpected parameters, want: %#v, got: %#v%s\n", *want, got, minimock.Diff(*want, got))
    		}
    
    		return
    
    	}
    	// here
    	mmReply.ReplyMock.mutex.Lock()
    	defer mmReply.ReplyMock.mutex.Unlock()
    	if mmReply.funcReply != nil {
    		mmReply.funcReply(ctx, origin, reply)
    		return
    	}
    	mmReply.t.Fatalf("Unexpected call to SenderMock.Reply. %v %v %v", ctx, origin, reply)
    
    }
    

    I'm not sure that it is the right solution. If so, I can make a pr

    Added: I've replaced code inside function to sleep to exclude races inside it

    sender.ReplyMock.Set(func(_ context.Context, receivedMeta payload.Meta, resMsg *message.Message) {
            time.Sleep(2 * time.Millisecond)
        })
    

    minimock version 2.1.9 Thanks!

  • Does not work without GOPATH env variable

    Does not work without GOPATH env variable

    Fails with error minimock: failed to detect import path of the ...: can't detect package for file: "..."

    Workaround is GOPATH=`go env GOPATH` minimock -i path -o bla bla

  • add v1.9.2 tag

    add v1.9.2 tag

    As v2 introduces API-breaking changes, we have a lot of code that can't yet move off v1. Please could you add a v1.9.2 tag (the same as the current 1.9.2 tag) so that v1 minimock plays better with Go modules? Thanks!

  • Follow Go Modules release versioning

    Follow Go Modules release versioning

    The latest version (v2.1.5) causes go list and some other tools to fail:

    $ go list
    go: errors parsing go.mod:
    /home/sergey/go/src/indeed.com/devops/snitch/go.mod:6: invalid module: github.com/gojuno/minimock should be v0 or v1, not v2 (v2.1.5)
    

    Using one of the approaches suggested in Releasing Modules (v2 or Higher) would resolve this.

    Workaround: depend on minimock using pseudo-versions as if it is not a proper go module. See this doc for details.

  • Allow for checking mocked calls by hand using a call history

    Allow for checking mocked calls by hand using a call history

    type Adder interface {
        Add(a int, b int) int
    }
    
    mock := NewAdderMock(mc)
    
    mock.Add(1, 2)
    mock.Add(3, 4)
    mock.Add(5, 6)
    
    // A 'Calls' attribute would contain an array of all the calls to Add()
    assert.Equal(t, 3, len(mock.AddMock.Calls))
    

    This example is somewhat useless since the arguments are known at runtime. But in cases where you may want to ignore certain arguments, or where the actual value of the arguments are not known, this would be extremely useful.

    A practical example of this would be testing a function which accepts a struct argument. You may only be interested in running assertions on a couple fields. Or perhaps the struct has a randomly generated field like a SessionID, and you want to verify that it's not blank. This would also provide a solution for #30.

    Additionally, there would need to be a way to disable expectation checking from mc.Finish() for a given mock. If you decide to use .Calls then that means you are handling the assertions yourself and not relying on the minimock methods. If you didn't disable the check, then you would receive an error saying that there was an unexpected call to the mock.

    This could look something like this:

    defer mc.Finish()
    mock := NewAdderMock(mc)
    mock.AddMock.Ignore()
    
    // Continue...
    
  • suffix flag has been removed

    suffix flag has been removed

    suffix = flag.String("s", "_mock_test.go", "output file name suffix which is added to file names when multiple interfaces are given") Hi, there was a suffix flag before switch to gowrap, it wasn't marked as deprecated. I would be very grateful if you could bring that flag back.

  • Test failures on 32 bit architectures

    Test failures on 32 bit architectures

    armv7hl: https://koji.fedoraproject.org/koji/taskinfo?taskID=73283110

          testing: github.com/gojuno/minimock
    github.com/gojuno/minimock
    PASS
    ok  	github.com/gojuno/minimock	0.011s
    github.com/gojuno/minimock/tests
    --- FAIL: TestFormatterMock_UnmockedCallFailsTest (0.00s)
    panic: unaligned 64-bit atomic operation
    	panic: unaligned 64-bit atomic operation [recovered]
    	panic: unaligned 64-bit atomic operation
    goroutine 7 [running]:
    testing.tRunner.func1.2(0x693728, 0x6bcdb0)
    	/usr/lib/golang/src/testing/testing.go:1143 +0x294
    testing.tRunner.func1(0x1c01880)
    	/usr/lib/golang/src/testing/testing.go:1146 +0x3b4
    panic(0x693728, 0x6bcdb0)
    	/usr/lib/golang/src/runtime/panic.go:965 +0x188
    runtime/internal/atomic.panicUnaligned()
    	/usr/lib/golang/src/runtime/internal/atomic/unaligned.go:8 +0x2c
    runtime/internal/atomic.Load64(0x1d12bac, 0x1c38508, 0x0)
    	/usr/lib/golang/src/runtime/internal/atomic/asm_arm.s:263 +0x14
    github.com/gojuno/minimock/tests.(*TesterMock).MinimockFatalfDone(0x1d12a80, 0x4cb101)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:931 +0xc4
    github.com/gojuno/minimock/tests.(*TesterMock).minimockDone(0x1d12a80, 0x0)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:998 +0x6c
    github.com/gojuno/minimock/tests.(*TesterMock).MinimockFinish(0x1d12a80)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:961 +0x1c
    panic(0x693728, 0x6bcdb0)
    	/usr/lib/golang/src/runtime/panic.go:965 +0x188
    runtime/internal/atomic.panicUnaligned()
    	/usr/lib/golang/src/runtime/internal/atomic/unaligned.go:8 +0x2c
    runtime/internal/atomic.Xadd64(0x1d12bb4, 0x1, 0x0, 0x4ed364, 0x6e4b70)
    	/usr/lib/golang/src/runtime/internal/atomic/asm_arm.s:233 +0x14
    github.com/gojuno/minimock/tests.(*TesterMock).Fatalf(0x1d12a80, 0x636e20, 0x2e, 0x1c0e220, 0x2, 0x2)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:854 +0x4c
    github.com/gojuno/minimock/tests.(*FormatterMock).Format(0x1d0e8a0, 0x637987, 0x32, 0x0, 0x0, 0x0, 0x0, 0x0)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/formatter_mock.go:186 +0x32c
    github.com/gojuno/minimock/tests.TestFormatterMock_UnmockedCallFailsTest(0x1c01880)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/formatter_mock_test.go:31 +0x128
    testing.tRunner(0x1c01880, 0x6bc52c)
    	/usr/lib/golang/src/testing/testing.go:1193 +0xd8
    created by testing.(*T).Run
    	/usr/lib/golang/src/testing/testing.go:1238 +0x254
    exit status 2
    FAIL	github.com/gojuno/minimock/tests	0.013s
    

    i686: https://koji.fedoraproject.org/koji/taskinfo?taskID=73283111

          testing: github.com/gojuno/minimock
    github.com/gojuno/minimock
    PASS
    ok  	github.com/gojuno/minimock	0.007s
    github.com/gojuno/minimock/tests
    --- FAIL: TestFormatterMock_UnmockedCallFailsTest (0.00s)
    panic: unaligned 64-bit atomic operation
    	panic: unaligned 64-bit atomic operation [recovered]
    	panic: unaligned 64-bit atomic operation
    goroutine 22 [running]:
    testing.tRunner.func1.2(0x5680ff60, 0x5683d574)
    	/usr/lib/golang/src/testing/testing.go:1143 +0x2ce
    testing.tRunner.func1(0x57082fc0)
    	/usr/lib/golang/src/testing/testing.go:1146 +0x3fc
    panic(0x5680ff60, 0x5683d574)
    	/usr/lib/golang/src/runtime/panic.go:971 +0x491
    runtime/internal/atomic.panicUnaligned()
    	/usr/lib/golang/src/runtime/internal/atomic/unaligned.go:8 +0x38
    runtime/internal/atomic.Load64(0x570d6bac, 0x570334d4, 0x0)
    	/usr/lib/golang/src/runtime/internal/atomic/asm_386.s:201 +0x10
    github.com/gojuno/minimock/tests.(*TesterMock).MinimockFatalfDone(0x570d6a80, 0x567b0b01)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:931 +0xab
    github.com/gojuno/minimock/tests.(*TesterMock).minimockDone(0x570d6a80, 0x567b0a15)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:998 +0x64
    github.com/gojuno/minimock/tests.(*TesterMock).MinimockFinish(0x570d6a80)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:961 +0x22
    panic(0x5680ff60, 0x5683d574)
    	/usr/lib/golang/src/runtime/panic.go:971 +0x491
    runtime/internal/atomic.panicUnaligned()
    	/usr/lib/golang/src/runtime/internal/atomic/unaligned.go:8 +0x38
    runtime/internal/atomic.Xadd64(0x570d6bb4, 0x1, 0x0, 0x570a26d0, 0x90)
    	/usr/lib/golang/src/runtime/internal/atomic/asm_386.s:107 +0x11
    github.com/gojuno/minimock/tests.(*TesterMock).Fatalf(0x570d6a80, 0x567bf08b, 0x2e, 0x570b2200, 0x2, 0x2)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/tester_mock_test.go:854 +0x48
    github.com/gojuno/minimock/tests.(*FormatterMock).Format(0x570d28a0, 0x567bfbf2, 0x32, 0x0, 0x0, 0x0, 0x0, 0x0)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/formatter_mock.go:186 +0x35e
    github.com/gojuno/minimock/tests.TestFormatterMock_UnmockedCallFailsTest(0x57082fc0)
    	/builddir/build/BUILD/minimock-3.0.9/_build/src/github.com/gojuno/minimock/tests/formatter_mock_test.go:31 +0x14d
    testing.tRunner(0x57082fc0, 0x5683ccf0)
    	/usr/lib/golang/src/testing/testing.go:1193 +0x102
    created by testing.(*T).Run
    	/usr/lib/golang/src/testing/testing.go:1238 +0x233
    exit status 2
    FAIL	github.com/gojuno/minimock/tests	0.011s
    
  • Simplify

    Simplify

    I use table tests and run each test inside a testing.T.Run closure and prefer to complete all test validation within the closure. To do this with minimock, I setup the mocks in my test cases with a nil minimock.Tester (NewXMock(nil)) and then within the closure, I do a type assertion on the mock, create a new controller, set the mock's tester and register the mock with the controller. Ex:

    tests := []struct {
    	name string
    	x        X // an interface
    	// additional test case details
    }{
    	{
    		name: "testName",
    		x:        NewXMock(nil),
    		// additional test case setup
    	},
    }
    for _, tt := range tests {
    	tt := tt
    	t.Run(tt.name, func(t *testing.T) {
    		if m, ok := tt.x.(*XMock); ok {
    			c := minimock.NewController(t)
    			defer c.Finish()
    			m.t = c
    			c.RegisterMocker(m)
    		}
    		// perform test
    	})
    }
    

    I would like to do something like:

    c := minimock.NewController(t)
    defer c.Finish()
    c.AttachMock(tt.x)
    

    Where AttachMock is defined like:

    func (c Controller) AttachMock(m interface{}) {
    	if m, ok := m.(interface{ SetTester(Tester) }); ok {
    		m.SetTester(c)
    	}
    }
    

    And generated mocks have:

    func (m *XMock) SetTester(t minimock.Tester) {
    	m.t = t
    
    	if controller, ok := t.(minimock.MockController); ok {
    		controller.RegisterMocker(m)
    	}
    }
    
  • Allow expected counter for concrete controller's method

    Allow expected counter for concrete controller's method

    Hi, I think there is an often case when we need to set expected times that concrete controller method will be executed during the test. Currently, <method>AfterCounter allows only to get the current value of calls to the mocked method, which is useless in table tests and lead to potential logical errors to pass the test.

    There is a convenient method Times(N) in gomock. Could you add a similar one?

  • Add parallel test scenario in README

    Add parallel test scenario in README

    Hi, when one executes tests in parallel with t.Parallel(), and does something like: defer mockController.Finish() (similar with Wait(<duration>) ) controller fails to recognize that some of mocks' Expect/Return and other patterns are not used. Without parallel tests, there would be error like: 'Expected to call .GetMock ...'

    To fix that, you need to use Cleanup method of testing.T and inside it call whether Finish or Wait.

    Could be implemented like in this issue https://github.com/gojuno/minimock/issues/62

    I think it'd be useful to add it in README, as go official docs aren't much informative

  • Use `t.Cleanup()` in constructor

    Use `t.Cleanup()` in constructor

    Now I have to remember to add defer or t.Cleanup in each test manually.

    func TestSomething(t *testing.T) {
      formatterMock := NewFormatterMock(t)
      defer formatterMock.Finish()
      ...
    }
    

    or

    func TestSomething(t *testing.T) {
      formatterMock := NewFormatterMock(t)
      t.Cleanup(formatterMock.Finish)
      ...
    }
    

    It would be great to do it automatically in mock constructor like gomock does. Of course only if it's go 1.14 or newer.

  • Comparison with gomock

    Comparison with gomock

    I am currently using the mockgen utility that comes with gomock to generate mocks for any interface (both inside the app and also for imported go modules)

    https://github.com/golang/mock

    A comparison of this tool and gomock+mockgen would be really awesome in my opinion

  • generating a file that doesn't compile

    generating a file that doesn't compile

    Minimock is generating a file that doesn't compile: go run github.com/gojuno/minimock/v3/cmd/minimock -g -i k8s.io/client-go/kubernetes/typed/core/v1.ServiceInterface

    The generated file is referencing a package (restclient) that isn't being imported.

    minimock version: v3.0.9 k8s.io/client-go version: v0.21.3

Vault mock - Mock of Hashicorp Vault used for unit testing

vault_mock Mock of Hashicorp Vault used for unit testing Notice This is a person

Jan 19, 2022
Mock-the-fck - Mock exercise for human

Mock the fck Originally, Mockery-example Example case for mockery issue #128 fil

Jan 21, 2022
A next-generation testing tool. Orion provides a powerful DSL to write and automate your acceptance tests

Orion is born to change the way we implement our acceptance tests. It takes advantage of HCL from Hashicorp t o provide a simple DSL to write the acceptance tests.

Aug 31, 2022
Merge Mock - testing tool for the Ethereum Merge

MergeMock Experimental debug tooling, mocking the execution engine and consensus node for testing. work in progress Quick Start To get started, build

Oct 21, 2022
A tool that integrates SQL, HTTP,interface,Redis mock

Mockit 目标:将mock变得简单,让代码维护变得容易 分支介绍 main 主分支,覆盖了单元测试 light 轻分支,去除了单元测试,简化了依赖项,方便其他团队使用 常见Mock难点 不同中间件,mock库设计模式不一致,学习代价高,差异化明显 mock方案强依赖服务端,无法灵活解耦 单元测试

Sep 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

Jan 3, 2023
Sql mock driver for golang to test database interactions

Sql driver mock for Golang sqlmock is a mock library implementing sql/driver. Which has one and only purpose - to simulate any sql driver behavior in

Dec 31, 2022
HTTP mock for Golang: record and replay HTTP/HTTPS interactions for offline testing

govcr A Word Of Warning I'm in the process of partly rewriting govcr to offer better support for cassette mutations. This is necessary because when I

Dec 28, 2022
Mock object for Go http.ResponseWriter

mockhttp -- Go package for unit testing HTTP serving Unit testing HTTP services written in Go means you need to call their ServeHTTP receiver. For thi

Sep 27, 2022
ESME is a go library that allows you to mock a RESTful service by defining the configuration in json format

ESME is a go library that allows you to mock a RESTful service by defining the configuration in json format. This service can then simply be consumed by any client to get the expected response.

Mar 2, 2021
mockery - A mock code autogenerator for Golang
mockery - A mock code autogenerator for Golang

mockery - A mock code autogenerator for Golang

Jan 8, 2023
Create your own mock server with just a JSON file!

Gmocker Run a blazing fast mock server in just seconds! ?? All you need is to make a json file that contains path and response mapping. See an example

Dec 21, 2022
Create your own blazing fast mock server with just a JSON file!

Gmocker Run a blazing fast mock server in just seconds! ?? All you need is to make a json file that contains path and response mapping. See an example

Dec 21, 2022
Dec 8, 2022
Completely type-safe compile-time mock generator for Go

Mockc Mockc is a completely type-safe compile-time mock generator for Go. You can use it just by writing the mock generators with mockc.Implement() or

Aug 25, 2022
A basic lightweight HTTP client for Go with included mock features.

A basic lightweight HTTP client for Go with included mock features. Features Support almost all http method like G

May 2, 2022
📡 mock is a simple, cross-platform, cli app to simulate HTTP-based APIs.
 📡 mock is a simple, cross-platform, cli app to simulate HTTP-based APIs.

mock ?? mock is a simple, cross-platform, cli app to simulate HTTP-based APIs. About mock Mock allows you to spin up a local http server based of a .m

May 6, 2022
A mock of Go's net package for unit/integration testing

netmock: Simulate Go network connections netmock is a Go package for simulating net connections, including delays and disconnects. This is work in pro

Oct 27, 2021
Mock API for REST!!!!

Mock API Server Introduction This app allows you to add urls and serve dummy json responses. It contains two handlers, the DummyHandler allows you to

Jun 20, 2022