Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

mock: hide implementation of Anything #1442

Open
dolmen opened this issue Jul 31, 2023 · 1 comment
Open

mock: hide implementation of Anything #1442

dolmen opened this issue Jul 31, 2023 · 1 comment
Assignees
Labels
enhancement pkg-mock Any issues related to Mock

Comments

@dolmen
Copy link
Collaborator

dolmen commented Jul 31, 2023

mock.Anything is currently implemented as:

const (
          // Anything is used in Diff and Assert when the argument being tested
          // shouldn't be taken into consideration. 
          Anything = "mock.Anything"
)

This has multiple problems:

  • the implementation details are public. This is a design mistake.
  • as the sentinel value is just an untyped string there is a non-zero risk of user code conflict

I propose to hide the implementation of Anything by making it a special value of a private type anything:

type anything struct{}

// Anything is used in Diff and Assert when the argument being tested
// shouldn't be taken into consideration. 
var Anything anything
@dolmen dolmen self-assigned this Jul 31, 2023
@dolmen dolmen added enhancement pkg-mock Any issues related to Mock labels Jul 31, 2023
@brackendawson
Copy link
Collaborator

This has bugged me every time I've seen it. I'm scared of this because is meets the definition of a breaking change, annoyingly.

Attention need to be paid to assertion failures where this string const is used, seeing it here annoys me too, and we can change this whenever we want, it's not breaking.

package main

import (
	"testing"

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

type myMock struct {
	mock.Mock
}

func (m *myMock) Do(stuff, things string) {
	m.Called()
}

func TestIfy(t *testing.T) {
	m := myMock{}
	m.Test(t)
	m.On("Do", mock.Anything, "cubes").Return()
	m.Do("anything", "spheres")
}

play

=== RUN   TestIfy
    mock.go:334: 
        
        mock: Unexpected Method Call
        -----------------------------
        
        Do()
        		
        
        The closest call I have is: 
        
        Do(string,string)
        		0: "mock.Anything"
        		1: "cubes"
        
        Provided 2 arguments, mocked for 0 arguments
        Diff: 0: PASS:  (Missing) == (string=mock.Anything)
        	1: FAIL:  (Missing) != (string=cubes)
--- FAIL: TestIfy (0.00s)
FAIL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement pkg-mock Any issues related to Mock
Projects
None yet
Development

No branches or pull requests

2 participants