Configuration¶
mockery uses spf13/viper under the hood for its configuration parsing.
Merging Precedence¶
The configuration applied to a specific mocked interface is merged according to the following precedence (in decreasing priority):
- Interface-specific config in .mockery.yaml
- Package-specific config in .mockery.yaml
- Command-line options
- Environment variables
- Top-level defaults in .mockery.yaml
Formatting¶
If a parameter is named with-expecter and we want a value of True, then these are the formats for each source:
| source | value | 
|---|---|
| command line | --with-expecter=true | 
| Environment variable | MOCKERY_WITH_EXPECTER=True | 
| yaml | with-expecter: True | 
Recommended Basic Config¶
Copy the recommended basic configuration to a file called .mockery.yaml at the top-level of your repo:
with-expecter: true
packages:
    github.com/your-org/your-go-project:
        # place your package-specific config here
        config:
        interfaces:
            # select the interfaces you want mocked
            Foo:
                # Modify package-level config for this specific interface (if applicable)
                config:
mockery will search upwards from your current-working-directory up to the root path, so the same configuration should be able to follow you within your project.
See the features section for more details on how the config is structured.
Parameter Descriptions¶
new style packages config
The packages config section is the new style of configuration. All old config semantics, including go:generate and any config files lacking the packages section is officially deprecated as of v2.31.0. Legacy semantics will be completely removed in v3.
Please see the features section for more details on how packages works, including some example configuration.
Please see the migration docs for details on how to migrate your config.
| name | templated | default | description | 
|---|---|---|---|
| all | false | Generate all interfaces for the specified packages. | |
| boilerplate-file | "" | Specify a path to a file that contains comments you want displayed at the top of all generated mock files. This is commonly used to display license headers at the top of your source code. | |
| config | "" | Set the location of the mockery config file. | |
| dir | "mocks/{{.PackagePath}}" | The directory where the mock file will be outputted to. | |
| disable-config-search | false | Disable searching for configuration files | |
| disable-version-string | false | Disable the version string in the generated mock files. | |
| dry-run | false | Print the actions that would be taken, but don't perform the actions. | |
| exclude | [] | Specify subpackages to exclude when using recursive: True | |
| filename | "mock_{{.InterfaceName}}.go" | The name of the file the mock will reside in. | |
| include-auto-generated | true | Set to falseif you need mockery to skip auto-generated files during its recursive package discovery. When set totrue, mockery includes auto-generated files when determining if a particular directory is an importable package. | |
| include-regex | "" | When set, only interface names that match the expression will be generated. This setting is ignored if all: Trueis specified in the configuration | |
| inpackage | false | When generating mocks alongside the original interfaces, you must specify inpackage: Trueto inform mockery that the mock is being placed in the same package as the original interface. | |
| mockname | "Mock{{.InterfaceName}}" | The name of the generated mock. | |
| outpkg | "{{.PackageName}}" | Use outpkgto specify the package name of the generated mocks. | |
| log-level | "info" | Set the level of the logger | |
| packages | null | A dictionary containing configuration describing the packages and interfaces to generate mocks for. | |
| print | false | Use print: Trueto have the resulting code printed out instead of written to disk. | |
| recursive | false | When set to trueon a particular package, mockery will recursively search for all sub-packages and inject those packages into the config map. | |
| tags | "" | Set the build tags of the generated mocks. | |
| with-expecter | true | Use with-expecter: Trueto generateEXPECT()methods for your mocks. This is the preferred way to setup your mocks. | |
| replace-type | null | Replaces aliases, packages and/or types during generation. | 
Layouts¶
Using different configuration parameters, we can deploy our mocks on-disk in various ways. These are some common layouts:
layouts
filename: "mock_{{.InterfaceName}}.go"
dir: "mocks/{{.PackagePath}}"
mockname: "Mock{{.InterfaceName}}"
outpkg: "{{.PackageName}}"
If these variables aren't specified, the above values will be applied to the config options. This strategy places your mocks into a separate mocks/ directory.
Interface Description
| name | value | 
|---|---|
| InterfaceName | MyDatabase | 
| PackagePath | github.com/user/project/pkgName | 
| PackageName | pkgName | 
Output
The mock will be generated at:
The mock file will look like:
Warning
Mockery does not protect against modifying original source code. Do not generate mocks using this config with uncommitted code changes.
filename: "mock_{{.InterfaceName}}.go"
dir: "{{.InterfaceDir}}"
mockname: "Mock{{.InterfaceName}}"
outpkg: "{{.PackageName}}"
inpackage: True
Instead of the mocks being generated in a different folder, you may elect to generate the mocks alongside the original interface in your package. This may be the way most people define their configs, as it removes circular import issues that can happen with the default config.
For example, the mock might be generated along side the original source file like this:
Interface Description
| name | value | 
|---|---|
| InterfaceName | MyDatabase | 
| PackagePath | github.com/user/project/path/to/pkg | 
| PackagePathRelative | path/to/pkg | 
| PackageName | pkgName | 
| SourceFile | ./path/to/pkg/db.go | 
Output
Mock file will be generated at:
The mock file will look like:
Templated Strings¶
mockery configuration makes use of the Go templating system.
Variables¶
Note
Templated variables are only available when using the packages config feature.
Variables that are marked as being templated are capable of using mockery-provided template parameters.
| name | description | 
|---|---|
| InterfaceDir | The directory path of the original interface being mocked. This can be used as dir: "{{.InterfaceDir}}"to place your mocks adjacent to the original interface. This should not be used for external interfaces. | 
| InterfaceDirRelative | The directory path of the original interface being mocked, relative to the current working directory. If the path cannot be made relative to the current working directory, this variable will be set equal to PackagePath | 
| InterfaceName | The name of the original interface being mocked | 
| InterfaceNameCamel | Converts a string interface_nametoInterfaceName.DEPRECATED: use {{ .InterfaceName | camelcase }}instead | 
| InterfaceNameLowerCamel | Converts InterfaceNametointerfaceName.DEPRECATED: use {{ .InterfaceName | camelcase | firstLower }}instead | 
| InterfaceNameSnake | Converts InterfaceNametointerface_name.DEPRECATED: use {{ .InterfaceName | snakecase }}instead | 
| InterfaceNameLower | Converts InterfaceNametointerfacename.DEPRECATED: use {{ .InterfaceName | lower }}instead | 
| Mock | A string that is Mockif the interface is exported, ormockif it is not exported. Useful when setting the name of your mock to something like:mockname: "{{.Mock}}{{.InterfaceName}}"This way, the mock name will retain the exported-ness of the original interface. | 
| MockName | The name of the mock that will be generated. Note that this is simply the mocknameconfiguration variable | 
| PackageName | The name of the package from the original interface | 
| PackagePath | The fully qualified package path of the original interface | 
Functions¶
Note
Templated functions are only available when using the packages config feature.
Template functions allow you to inspect and manipulate template variables.
All template functions are calling native Go functions under the hood, so signatures and return values matches the Go functions you are probably already familiar with.
To learn more about the templating syntax, please see the Go text/template documentation
- containsstring substr
- hasPrefixstring prefix
- hasSuffixstring suffix
- joinelems sep
- replacestring old new n
- replaceAllstring old new
- splitstring sep
- splitAfterstring sep
- splitAfterNstring sep n
- trimstring cutset
- trimLeftstring cutset
- trimPrefixstring prefix
- trimRightstring cutset
- trimSpacestring
- trimSuffixstring suffix
- lowerstring
- upperstring
- camelcasestring
- snakecasestring
- kebabcasestring
- firstLowerstring
- firstUpperstring
- matchStringpattern
- quoteMetastring
- basestring
- cleanstring
- dirstring
- expandEnvstring
- getenvstring
Legacy config options¶
legacy configuration options
The legacy config options will be removed in v3 and are deprecated (but supported) in v2.
| name | description | 
|---|---|
| all | It's common for a big package to have a lot of interfaces, so mockery provides all. This option will tell mockery to scan all files under the directory named by--dir("." by default) and generates mocks for any interfaces it finds. This option impliesrecursive: True. | 
| boilerplate-file | Specify a path to a file that contains comments you want displayed at the top of all generated mock files. This is commonly used to display license headers at the top of your source code. | 
| case | mockery generates files using the casing of the original interface name.  This can be modified by specifying case: underscoreto format the generated file name using underscore casing. | 
| exclude | This parameter is a list of strings representing path prefixes that should be excluded from mock generation. | 
| exported | Use exported: Trueto generate public mocks for private interfaces. | 
| filename | Use the filenameandstructnameto override the default generated file and struct name. These options are only compatible with non-regular expressions inname, where only one mock is generated. | 
| inpackage-suffix | When inpackage-suffixis set toTrue, mock files are suffixed with_mockinstead of being prefixed withmock_for InPackage mocks | 
| inpackageandkeeptree | For some complex repositories, there could be multiple interfaces with the same name but in different packages. In that case, inpackageallows generating the mocked interfaces directly in the package that it mocks. In the case you don't want to generate the mocks into the package but want to keep a similar structure, use the optionkeeptree. | 
| name | The nameoption takes either the name or matching regular expression of the interface to generate mock(s) for. | 
| output | mockery always generates files with the package mocksto keep things clean and simple. You can control which mocks directory is used by usingoutput, which defaults to./mocks. | 
| outpkg | Use outpkgto specify the package name of the generated mocks. | 
| print | Use print: Trueto have the resulting code printed out instead of written to disk. | 
| recursive | Use the recursiveoption to search subdirectories for the interface(s). This option is only compatible withname. Thealloption impliesrecursive: True. | 
| replace-type source=destination | Replaces aliases, packages and/or types during generation. | 
| testonly | Prepend every mock file with _test.go. This is useful in cases where you are generating mocksinpackagebut don't want the mocks to be visible to code outside of tests. | 
| with-expecter | Use with-expecter: Trueto generateEXPECT()methods for your mocks. This is the prefervar(--md-code-hl-number-color) way to setup your mocks. |