I am new to Go. I am using GoMock to assist with testing. The main question I have is am I supposed to modify the generated go mock file to test my functions?
As I understand, I must pass a mock controller to a new mock of the type I want to test such as this:
mockMale := mock.NewMockMale(ctl)
// insert expectations
user := NewUser(mockMale)
err := user.GetUserInfo(id)
However, I am confused regarding the testing the implementation. In this example, let’s look at u.Person.Get(id)
.
package user
import "github.com/EDDYCJY/mockd/person"
type User struct {
Person person.Male
}
func NewUser(p person.Male) *User {
return &User{Person: p}
}
func (u *User) GetUserInfo(id int64) error {
return u.Person.Get(id)
}
I understand that the reason GetUserInfo(id int64)
exists is so that I can call the Get(id)
.
I get the impression that GetUserInfo must include Person.Get(id) because the mock is expecting that, but then how do I include my custom implementation of Get(id)
If Person.Get(id), is always called? Am I supposed to modify the mock method of Getid() that was generated using gomock?
func (u *User) Get(id int64) error {
if a == 2 {
func1()
} else {
func2()
}
}
Person.Male:
package person
type Male interface {
Get(id int64) error
}
6
The issue with your code is that you need to tell the mock that you have an expected caller called “Get”
var id float64 = 3
mockMale := mock.NewMockMale(ctl)
mockMale.EXPECT().Get(id).Return(nil).Times(1) // here you are expecting your called function to return a nil error, and called one time
// insert expectations
user := NewUser(mockMale)
err := user.GetUserInfo(id)
Without that you would have a failed test