agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.96k stars 179 forks source link

add convenient Patches constructor #3

Closed bbrodriges closed 5 years ago

bbrodriges commented 5 years ago

Currently there is no way to construct Patches object to pass different doubles for different targets, e.g. :

patchFuncs := [][2]interface{}{
    {
        amqp.Dial,
        func(url string) (*amqp.Connection, error) {
            return nil, testAmqpDialError
        },
    },
    {
        lepus.SyncChannel,
        func(*amqp.Channel, error) (*lepus.Channel, error) {
            return nil, testAmqpChannelError
        },
    }
}

patches := new(gomonkey.Patches) // will not call make unexported maps
for _, patchPair := range patchFuncs {
    patches.ApplyFunc(pair[0], pair[1]) // will panic "assignment to nil map"
}
defer patches.Reset()

With this simple wrapper around create() func it will be possible:

patches := gomonkey.NewPatches() // will call make on unexported maps
for _, patchPair := range patchFuncs {
    patches.ApplyFunc(pair[0], pair[1]) // will not panic
}
defer patches.Reset()
agiledragon commented 5 years ago

I also think it is a better way!