1

I've mocked a repository interface and I want to return a specific value when a method is called. However, it always returns what's in the dummy implementation.

type MockUserRepo struct {
  mock.Mock
}

// dummy method to fulfil the interface
func (m *MockUserRepo) FindByUsername(username string) (*User, error) {
    return nil, nil 
}

Now, I setup the mock as such

m := NewMockUserRepo()
m.On("FindByUsername", mock.Anything).Return(&User{
    Username: "test"
}, nil)

// inject mock
svc := NewService(m)
user, err := svc.FindByUsername("anything") // always nil,nil

The return value (user, err) is always nil (or whatever is returned in MockUserRepo.FindByUsername

Is there something I'm doing wrong?

Acha Bill
  • 1,255
  • 1
  • 7
  • 20
  • 3
    *"Is there something I'm doing wrong?"* -- Yes. Compare your implementation of `*MockUserRepo.FindByUsername` to that of the package's example usage doc: [`*MyTestObject.SavePersonDetails`](https://pkg.go.dev/github.com/stretchr/testify/mock#hdr-Example_Usage) (basically you're missing the `Called()` and the `args.Get(0).(*User)`) – mkopriva Aug 20 '22 at 06:25
  • But `args.Get(0)` is `string`. Not `*User`. Basically, I don't care about the args. – Acha Bill Aug 20 '22 at 09:51
  • *"But `args.Get(0)` is `string`"*. [It is not](https://go.dev/play/p/5BMEO5BO7Ml). You haven't even tried to type in the two suggested lines and execute to code to see it pass. Why? The word "args" doesn't necessarily have to mean input arguments, there's also such a thing as "return argument". – mkopriva Aug 20 '22 at 10:06
  • https://pkg.go.dev/github.com/stretchr/testify/mock#Arguments => *"Arguments holds an array of method arguments or **return values**."* – mkopriva Aug 20 '22 at 10:13

1 Answers1

0

source : https://pkg.go.dev/github.com/stretchr/testify/mock#hdr-Example_Usage

For objects of your own type, use the generic Arguments.Get(index) method and make a type assertion: return args.Get(0).(*MyObject), args.Get(1).(*AnotherObjectOfMine)

So in your FindByUsername method change to this:

func (m *MockUserRepo) FindByUsername(username string) (*User, error) {
    args := m.Called(username)
    return args.Get(0).(*User), args.Error(1)
}

playground

Rahmat Fathoni
  • 1,272
  • 1
  • 2
  • 8