Home >Backend Development >Golang >Gomock did not return the expected value
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") }
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?
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.
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!