Skip to content

mock does not enforce arity if parameter is Anything #587

Closed

Description

@dnathe4th
package main_test

import (
	"testing"

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

type Foo interface {
	Bar()
}

type MockFoo struct {
	mock.Mock
}

// Bar provides a mock function with given fields:
func (_m *MockFoo) Bar() {
	_m.Called()
}

func TestFoo(t *testing.T) {
	foo := new(MockFoo)
	foo.On("Bar", mock.Anything).Return()

	foo.Bar() // expected error for unmocked call
}

The logic in Arguments.Diff does not check whether a given argument is required by the function signature before checking if the value is Anything. Phrased another way, there is no explicit arity check on the mocked method.

Activity

  1. devdinu commented on Apr 6, 2018

    @devdinu
    Contributor

    We could also think about failing the setup of expectation, when the On(expectation) and Bar(actual) arity mismatches. we should also consider variardic in it. This could be a separate PR or enhancement.

  2. dnathe4th commented on Apr 6, 2018

    @dnathe4th
    Author

    I do think that is a better solution than what I ended up with. I implemented the check in Diff solely because that was the only part of the library I was familiar with. Let me see what kind of type checking we have in On(expectation) I can extend for this purpose.

  3. dnathe4th commented on Apr 6, 2018

    @dnathe4th
    Author

    So my reflect-fu may be weak, but I don't believe your proposal is possible. Since On(expectation) is defined on *mock.Mock it has no access to the actual struct embedding mock.Mock. I don't believe there is any way to get the actual underlying implementation on methodName to check argument count against. Am I missing something?

  4. devdinu commented on Apr 11, 2018

    @devdinu
    Contributor

    @dnathe4th Yep, agreed its not possible in current On method, since we've reference to *mock.Mock type and the other methods isn't available via reflection.
    i've also tried whether we could get the information with reflection, but i couldn't find any.

    But for the above proposal, i am thinking of

    (m *Mock) OnFunc(f reflect.Func, arguments)
    

    This would enable us to have a strict mocking and argument verification, and helps in case of renaming function etc.

  5. ernesto-jimenez commented on Jun 9, 2018

    @ernesto-jimenez
    Member

    @devdinu how would that work?

    Requiring people to use the reflect package on their tests sounds like would lead to messy tests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    mock.ArgumentMatcherAbout matching arguments in mockpkg-mockAny issues related to Mock

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions