Skip to content

replace-type:

v3.0.0

The replace-type: parameter allows you to replace a type in the generated mocks with another type. Take for example the following interface:

interface.go
package replace_type

import (
    "github.com/vektra/mockery/v3/internal/fixtures/example_project/replace_type/rti/rt1"
    "github.com/vektra/mockery/v3/internal/fixtures/example_project/replace_type/rti/rt2"
)

type RType interface {
    Replace1(f rt1.RType1)
}

You can selectively replace the rt1.RType1 with a new type if so desired. For example:

Schema

.mockery.yml
replace-type:
  github.com/vektra/mockery/v3/internal/fixtures/example_project/replace_type/rti/rt1:
    RType1:
      pkg-path: github.com/vektra/mockery/v3/internal/fixtures/example_project/replace_type/rti/rt2
      type-name: RType2

Inheritance

replace-type is inherited like most other parameters: entries set at the root level apply to every package, and entries set at the package level apply to every interface in that package. Entries defined closer to the interface take precedence over inherited entries for the same package path and type name; entries for other types are merged.

Warning

Before this was supported, a root-level replace-type was silently ignored. Existing configs that set one will now see it applied to every package.

Result

The mock will now replace all instances of rt1.RType1 with rt2.RType2. You can see the before and after of mockery-style mocks:

Go
// Replace2 provides a mock function for the type RTypeReplaced1
func (_mock *RTypeReplaced1) Replace1(f rt1.RType1) {
    _mock.Called(f)
    return
}
Go
// Replace2 provides a mock function for the type RTypeReplaced1
func (_mock *RTypeReplaced1) Replace1(f rt2.RType2) {
    _mock.Called(f)
    return
}

Background

This parameter is useful if you need to need to work around packages that use internal types. Take for example the situation found here, noted by RangelReale.

If the internal types are re-exported through public type aliases, resolve-internal-aliases can do this mapping automatically.