简体   繁体   中英

How to mock one of the struct methods?

I have

type Service struct {
    config *config.Config
    model  *model.DB
    gates  *config.Gates
    rdb    *redis.Client
}

where

type DB struct {
    *sql.DB
}

How to mock one of the struct methods? Without touching the other methods.

func (e *Service) FindGateErrorId(gate, errorCode, errorMessage string, eventObj model.EventObj) (string, error) {
if errorFormat, err := e.model.GetServiceParam(eventObj.ServiceId, "error_format", eventObj.IsTest); err != nil {
        return "", err
//some code
}

Make the type that you want to mock implement an interface. Then wherever you use that type replace the variable to that type with a variable to the interface that the type implements. Now any type implementing that interface can be swapped in. To mock just one method, but not the others wrap the non-mock type with the mock. Let all other implemented methods in the mock simply call the wrapped type. For the method you want to mock implement the logic you desire.

type Animal interface {
    Say()
    Eat()
}

type Cat struct {}

func (c Cat) Say() {
    fmt.Println("meow")
}

func (c Cat) Eat() {
    fmt.Println("yum cat food meow")
}

type FunkyCatMock struct {
    wrapped Cat
}

func (m FunkyCatMock) Say() {
    fmt.Println("woof")
}

func (m FunkyCatMock) Eat() {
    m.wrapped.Eat()
}

func main() {
    var cat Animal
    var mock Animal

    cat = Cat{}

    mock = FunkyCatMock {
        wrapped: Cat{},
    }

    cat.Say()
    cat.Eat()
    mock.Say()
    mock.Eat()
}

Another thing to keep in mind is that if you find that you are putting many methods into one interface you should consider how you could break that interface into smaller ones. This would be more idiomatic Go.

For example:

type Writer interface {
    Write(p []byte) (n int, err error)
}

Go uses structural typing which is similar to duck typing in that if it looks like a duck and it quacks like a duck then it must be a duck.

The reason I bring this up is that it may be the case that you could define a very narrow interface and not have to worry about the mock implementing the other methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM