counterfeiter

repository·main·Indexed 22 days ago

https://github.com/maxbrunsfeld/counterfeiter

A Go tool for automatically generating test doubles (fakes) for interfaces. It integrates with `go generate` and supports standard directives, batch generation via the `-generate` flag, and manual shell invocation for third-party interfaces. The tool provides features for stubbing return values, recording arguments, and verifying call counts in unit tests.

Tokens
1.5K
Snippets
6
Records
7
Agent score
28%

What's inside counterfeiter

  1. Install counterfeiter as a tool dependency

    main

    The recommended way to use counterfeiter is as a tool dependency within a Go module. This ensures your team uses the same version and allows you to invoke it via go tool counterfeiter.

    Note: These instructions assume you are using Go 1.24 or later. If you are using Go 1.23 or earlier, refer to the older documentation.

    go get -tool github.com/maxbrunsfeld/counterfeiter/v6
  2. Generate test doubles using go:generate directives

    main

    To keep test doubles in sync with your interfaces, use go:generate directives in your .go files. You can use two different patterns:

    Standard Directive

    Add a directive directly above your interface. This is useful for single interfaces.

    If a package contains many interfaces, use the -generate flag once per package to speed up the process. Then, use the //counterfeiter:generate shorthand for each interface.

    To run the generation, execute go generate ./... from your module root.

    package foo
    
    // Option 1: Standard directive
    //go:generate go tool counterfeiter . MySpecialInterface
    type MySpecialInterface interface {
    	DoThings(string, uint64) (int, error)
    }
    
    // Option 2: Batch generation (faster for many interfaces)
    //go:generate go tool counterfeiter -generate
    
    //counterfeiter:generate . MyOtherInterface
    type MyOtherInterface interface {
    	DoOtherThings(string, uint64) (int, error)
    }
  3. Generate test doubles using the `//counterfeiter:generate` directive

    main

    Counterfeiter supports a code generation mode where it scans your Go files for specific directives. You can trigger the generation of a test double for an interface by adding a comment line starting with //counterfeiter:generate followed by the necessary arguments (typically the interface name or path).

    When running in this mode, Counterfeiter will find all Go files in the current directory (including Cgo and test files) and execute the generation for every matching directive found.

    //counterfeiter:generate github.com/example/pkg.MyInterface
  4. Use generated test doubles in your tests

    main

    Once generated, import the foofakes package (or whatever directory you specified) to use the fake implementation in your unit tests.

    Common Patterns

    • Instantiation: Create a pointer to the fake struct.
    • Recording Arguments: Use ArgsForCall(n) to inspect the arguments passed to a specific call index.
    • Checking Call Counts: Use DoThingsCallCount() to verify how many times a method was invoked.
    • Stubbing Returns: Use DoThingsReturns(...) to define what the fake should return when called.
    import "my-repo/path/to/foo/foofakes"
    
    // 1. Instantiate
    var fake = &foofakes.FakeMySpecialInterface{}
    
    // 2. Stub return values
    fake.DoThingsReturns(3, errors.New("the-error"))
    
    // 3. Execute and verify
    num, err := fake.DoThings("stuff", 5)
    
    // 4. Inspect calls
    // Check call count
    // fake.DoThingsCallCount()
    
    // Check arguments of the first call (index 0)
    str, num := fake.DoThingsArgsForCall(0)
  5. Configure counterfeiter via environment variables

    main

    You can control the behavior of the counterfeiter CLI using several environment variables:

    • COUNTERFEITER_PROFILE: If set to a non-empty value, the tool will generate a CPU profile named counterfeiter.profile in the current directory.
    • COUNTERFEITER_DEBUG: Enables debug mode, which causes the tool to log more detailed information to stderr and ensures logs are not discarded.
    • COUNTERFEITER_DISABLECACHE: Disables the internal caching mechanism. When set, the tool uses FakeCache and SimpleFileReader instead of the standard Cache and CachedFileReader.
    • COUNTERFEITER_NO_GENERATE_WARNING: Suppresses the warning message that appears when invoking counterfeiter multiple times via go generate.
  6. Reference: counterfeiter CLI flags

    main

    When invoking counterfeiter directly via the shell, the following flags are available:

    • -generate: Enables batch generation mode.
    • -o <output-path>: Specifies the output path for the generated file.
    • -p: (Internal/Specific use case)
    • --fake-name <fake-name>: Sets a custom name for the generated fake.
    • -header <header-file>: Specifies a file to use as a header for the generated code.
    • <source-path>: The path to the package containing the interface.
    • <interface>: The name of the interface to mock.
    USAGE
    	counterfeiter
    		[-generate] [-o <output-path>] [-p] [--fake-name <fake-name>]
    		[-header <header-file>]
    		[<source-path>] <interface> [-]
  7. Invoke counterfeiter from the shell

    main

    You can invoke counterfeiter manually using the go tool command. This is useful for generating doubles for third-party interfaces or specific paths without using directives.

    Syntax for Third-Party Interfaces

    To generate a double for an interface from an external package, use the <package>.<interface> syntax.

    # Generate for a local interface
    go tool counterfeiter path/to/foo MySpecialInterface
    
    # Generate for a third-party interface
    go tool counterfeiter github.com/go-redis/redis.Pipeliner