4 ms·
Java and co can generate logic at runtime, go cannot so you have to manually write mocks, or "generate" them with a third party executable. You cannot mock any
by camus2 9y ago
Java and co can generate logic at runtime, go cannot so you have to manually write mocks, or "generate" them with a third party executable.
You cannot mock anything if you don't use go interfaces at first place, there is no inheritance in go so you can't swap types unless they are interfaces or convertible.
given an interface Fooer :
type Fooer interface {
Do(int)int
}
and a method to test
func Accept(f Fooer){
f.Do(10)
}
it's easy to write a mock
type FooImpl struct {
T testing.T
}
func(f FooImpl)Do(i int)int{
f.T.Helper()
if i!=10{
f.T.Fail("i=10 expected")
}
return 0
}
// the test
func TestAccept(t testing.T){
Accept(FooImpl{T:t})
}
Again, your methods have to accept interfaces at first place or you can't mock anything. With Go you'll often have to step back and do manually the things you took for granted in Java.
Only go maintainers can fix the "issue", by allowing the method definition on ad hoc structs, which is impossible right now.