go-redis / redismock

Redis client Mock
https://redis.uptrace.dev
BSD 2-Clause "Simplified" License
284 stars 63 forks source link

Why mock with no expectations not failing #12

Open henrikrudstrom opened 3 years ago

henrikrudstrom commented 3 years ago

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?

monkey92t commented 3 years ago

All expected commands have been executed.

henrikrudstrom commented 3 years ago

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?

monkey92t commented 3 years ago

You will receive the error returned by the command.

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

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)

agileman-droid commented 2 years ago

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

antonyho commented 5 months ago

Can we add a function for reporting unexpected command calls into the Expect interface?

Here is my proposal Pull Request: https://github.com/go-redis/redismock/pull/91