Ability to have a single mock implement multiple interfaces
jpopadak opened this issue ยท 5 comments
For some Go code, a single struct might implement multiple interfaces.
For example:
type IType1 interface {
Method1() error
}
type IType2 interface {
Method2() string
}
func DoWork(input IType1) error {
if err := input.Method1(); err != nil {
return err
}
if i2, ok := input.(IType2); !ok {
return error.New("does not implement IType2")
}
fmt.Println(i2.Method2())
return nil
}
This helps with plug and play code, where you are accepting outside objects to execute logic on more than one interface.
Suggested generate command can be:
pegomock generate github.com/path/to/pkg IType1 github.com/path/to/other/pkg IType2
Hey @jpopadak, very interesting use case. Have you worked around it so far by defining a interface along the lines of
type IType12 interface {
IType1
IType2
}
And generating the mock based on that or how did you work around it?
From the top of my head I don't remember if the command you suggested is unambiguous, specifically because in the past you could generate multiple mocks by specifying multiple interfaces. Have you checked?
I have not tried doing that, although that could work too.
In my case, there were only 2 methods, one for each interface, so I created a stub struct with the implemented methods as needed.
@jpopadak So I've checked the CLI: in theory it's possible to implement the command you suggested. However, I'm not convinced yet, that we should really add it: it will make the generate
command quite a bit more complex. Not only implementation-wise, but also its usage, because you can now provide multiple space-separated interfaces + prefix each one with a package path, also space-separated. I think there is real potential for a user to get this wrong without understanding what is actually wrong. Compared to that, adding a compound interface to your test package as I suggested above seems like the lesser evil. What do you think?
I honestly think the best route forward is the one you suggested here: #81 (comment)
Might be useful in your documentation, but it's an obvious solution I didn't think about. ๐
Agree, that could be part of the documentation. Let's leave this issue open and I'll see where it fits in best. (Will probably take a little longer this time as I'm a bit busy...)