vektra / mockery

A mock code autogenerator for Go
https://vektra.github.io/mockery/
BSD 3-Clause "New" or "Revised" License
6.09k stars 409 forks source link

Invalid code generation when interface method parameter is named _ #415

Open patrick246 opened 3 years ago

patrick246 commented 3 years ago

Observed behavior

When generating mocks for an interface like this

package test

//go:generate mockery --name Test
type Test interface {
  Test(_ int)
}

the generated code looks like this

// Code generated by mockery v2.9.4. DO NOT EDIT.

package mocks

import mock "github.com/stretchr/testify/mock"

// Test is an autogenerated mock type for the Test type
type Test struct {
    mock.Mock
}

// Test provides a mock function with given fields: _
func (_m *Test) Test(_ int) {
    _m.Called(_)
}

The problem here is, that the call _m.Called(_) uses the _ like an actual variable.

Expected behavior

I expected the generated code to look like this

// Code generated by mockery v2.9.4. DO NOT EDIT.

package mocks

import mock "github.com/stretchr/testify/mock"

// Test is an autogenerated mock type for the Test type
type Test struct {
    mock.Mock
}

// Test provides a mock function with given fields: _
func (_m *Test) Test(mockeryParam0 int) {
    _m.Called(mockeyParam0)
}

that is, to replace the invalid parameter name with an autogenerated value.

Workaround

Of course, this is solved by giving the parameter in the interface an actual name. However, I think that valid Go code should not cause mockery to generate invalid Go code.

SVilgelm commented 2 years ago

you can ignore the parameter's name at all in the interfaces:

package test

//go:generate mockery --name Test
type Test interface {
  Test(int)
}

it generates this code:

// Code generated by mockery v2.9.4. DO NOT EDIT.

package mocks

import mock "github.com/stretchr/testify/mock"

// Test is an autogenerated mock type for the Test type
type Test struct {
    mock.Mock
}

// Test provides a mock function with given fields: _a0
func (_m *Test) Test(_a0 int) {
    _m.Called(_a0)
}