redismock icon indicating copy to clipboard operation
redismock copied to clipboard

Why mock with no expectations not failing

Open henrikrudstrom opened this issue 3 years ago • 6 comments

This package looks awesome, but i would have expected these tests to fail:

package frontpage_test

import (
	"context"
	"testing"

	"github.com/go-redis/redismock/v8"
	. "github.com/onsi/ginkgo"

	. "github.com/onsi/gomega"
)

func TestFrontpage(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Frontpage Suite")
}

var _ = FDescribe("Reader", func() {
	It("should fail", func() {
		redisCli, redisMock := redismock.NewClientMock()
                 // No expectations set, so this should fail right?
		_ = redisCli.Set(context.TODO(), "key", "value", 0).Err()

		Expect(redisMock.ExpectationsWereMet()).To(BeNil())
	})

	It("should fail", func() {
		redisCli, redisMock := redismock.NewClientMock()
                 // just setting an expectation that is fullfilled, to see if that helps...
		redisMock.ExpectPing()
		redisCli.Ping(context.TODO())
		_ = redisCli.Set(context.TODO(), "key", "value", 0).Err()

		Expect(redisMock.ExpectationsWereMet()).To(BeNil())
	})
})

Im calling a Set that is not expected, why is that not failing?

henrikrudstrom avatar May 20 '21 19:05 henrikrudstrom

All expected commands have been executed.

monkey92t avatar May 21 '21 02:05 monkey92t

ok, but shouldnt it fail, or, it would be nice to set it up to fail if a command is executed that should not be executed. In my case i want to ensure nothing is written to redis in certain cases. is there a way to set that up?

henrikrudstrom avatar May 21 '21 09:05 henrikrudstrom

You will receive the error returned by the command.

// fail
err = redisCli.Set(context.TODO(), "key", "value", 0).Err()
Expect(err).NotTo(HaveOccurred())

monkey92t avatar May 21 '21 10:05 monkey92t

ah. thats how it is intended. Unfortunately that doesnt solve my case. the method im testing is handling the error (and not returning it), so i wont be able to assert that Set was never called.

i like the behaviour of testify (https://github.com/stretchr/testify). it panics when an unexpected method is called, causing the test to fail.

Would be nice to be have a toggle that panics instead of returning an error mock.PanicOnUnexpectedCall(true) or somthing. Happy to provide a PR for that. (i guess its a matter of adding an if statement around here: https://github.com/go-redis/redismock/blob/master/mock.go#L153)

henrikrudstrom avatar May 21 '21 11:05 henrikrudstrom

Running into the same issue. It's quite confusing that the mock does not fail on unexpected method calls.

agileman-droid avatar Feb 28 '22 12:02 agileman-droid