stretchr / testify

A toolkit with common assertions and mocks that plays nicely with the standard library
MIT License
23.09k stars 1.58k forks source link

mock.MatchedBy cannot match against context.Context, always get Unexpected Method Call #645

Closed abhinav3295 closed 5 years ago

abhinav3295 commented 6 years ago

I am trying to mock a function that has context.Context as an argument. But when I use mock.Anything tests run fine, but on using mock.MatchedBy I am always getting Unexpected Method Call

func TestSomeClass_funcA(t *testing.T) {
    helper := MockHelper{}
    helper.On("funcA", mock.MatchedBy(func(ctx context.Context) bool {
        return ctx.Value("foo-bar") != nil
    })).Return(true)
    main := MainClass{
        helper: helper,
    }
    assert.True(t, main.funcMain())
}

sample project to reproduce the bug is attached. reproduceStrecherBug.zip

devdinu commented 6 years ago

@abhinav3295 You've to add the value to the context before calling funcA.

    ctx := context.Background()
    ctx = context.WithValue(ctx, "asas", "some")
    return m.helper.funcA(ctx)

makes the test pass.

Thanks for sharing the code which's easy to reproduce and help 👍

rbtcollins commented 5 years ago

Perhaps this bug should get closed?

abhinav3295 commented 5 years ago

Thanks!