Home > Backend Development > Golang > Gomock did not return the expected value

Gomock did not return the expected value

PHPz
Release: 2024-02-05 22:15:04
forward
1116 people have browsed it

Gomock 未返回预期值

Question content

I am an experienced programmer, but still new to go. I'm writing some logging tests and for these purposes I generated a mock of the logsink class (using mockgen ). Since that part is all automatically generated, I think we can assume there aren't any issues there.

This is my test code:

func TestLogging(t *testing.T) {
    ls := mock.NewMockLogSink(gomock.NewController(t))
    ls.EXPECT().Init(gomock.Any())
    const logLevel = 1
    ls.EXPECT().Enabled(gomock.Any()).AnyTimes().Do(func(level int) bool {
        return level <= logLevel
    })
    log.Set(logr.New(ls))
    ls.EXPECT().Info(gomock.Any(), "Foo").Times(1)
    log.Info("Foo")
    ls.EXPECT().Info(gomock.Any(), "Bar").Times(0)
    log.V(2).Info("Bar")
}
Copy after login

But this test fails because the "foo" log is never called. I stepped through the code and found that my expect().do() code was called as expected and returned true, but in the mock code it would logger The result of .sink.enabled() is treated as false!

What did i do wrong? Am I missing a secret switch?


Correct answer


Well, it turns out that .do() intentionally ignores the return value. Here is the documentation in the code:

// Do declares the action to run when the call is matched. The function's
// return values are ignored to retain backward compatibility. To use the
// return values call DoAndReturn.
Copy after login

Backward compatibility. correct. A bloody pit of public domain, if you ask me...

The above is the detailed content of Gomock did not return the expected value. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template