github.com/maxbrunsfeld/counterfeiter/fixtures/dup_packages

A tool for generating self-contained, type-safe test doubles in go


License
MIT
Install
go get github.com/maxbrunsfeld/counterfeiter/fixtures/dup_packages

Documentation

Counterfeiter

Build Status

When writing unit-tests for an object, it is often useful to have fake implementations of the object's collaborators. In go, such fake implementations cannot be generated automatically at runtime. This tool allows you to generate them before compilation.

Generating fakes

Choose an interface for which you would like a fake implementation:

$ cat path/to/foo/something.go
package foo

type Something interface {
    DoThings(string, uint64) (int, error)
    DoNothing()
}

Run counterfeiter like this:

$ counterfeiter path/to/foo Something
Wrote `FakeSomething` to `path/to/foo/foofakes/fake_something.go`

You can customize the location of the ouptut using the -o flag, or write the code to standard out by providing - as a third argument.

If you'd like a fake implementation for an interface you do not own you can do that too by providing only a fully qualified import path:

$ counterfeiter some/imported/package.Something
Wrote `FakeSomething` to `current/directory/fakes/fake_something.go`

Using the fake in your tests

Instantiate fakes with new:

import "my-repo/path/to/foo/foofakes"

var fake = new(foofakes.FakeSomething)

Fakes record the arguments they were called with:

fake.DoThings("stuff", 5)

Expect(fake.DoThingsCallCount()).To(Equal(1))

str, num := fake.DoThingsArgsForCall(0)
Expect(str).To(Equal("stuff"))
Expect(num).To(Equal(uint64(5)))

You can set their return values:

fake.DoThingsReturns(3, errors.New("the-error"))

num, err := fake.DoThings("stuff", 5)
Expect(num).To(Equal(3))
Expect(err).To(Equal(errors.New("the-error")))

You can also supply them with stub functions:

fake.DoThingsStub = func(arg1 string, arg2 uint64) (int, error) {
    Expect(arg1).To(Equal("stuff"))
    Expect(arg2).To(Equal(uint64(5)))
    return 3, errors.New("the-error")
}

num, err := fake.DoThings("stuff", 5)

Expect(num).To(Equal(3))
Expect(err).To(Equal(errors.New("the-error")))

License

Counterfeiter is MIT-licensed.