mardi 4 août 2020

How to mock Database methods in Golang

I am new to testing in general and cannot figure out, what would be a good way to add testing to my snippets of code without having to read/write to the Database.

Just for an example, one of the components of my application is a messaging feature.

This is the createMessage handler:

    m, err := doa.AddTextMessage(ctx, client, index, chatID, senderID, text)

    if err != nil {
        fmt.Println("Could not add Text Message to db")
        return nil, err
    }

    fmt.Println("Insertion Successful")
    return m, nil

doa represents the Data Object Access . It is basically acting as an abstraction, so that if ever I need to use another database, I won't have to change this code, just the underlying implementation.

My DOA method: AddTextMessage is as follows:

func AddTextMessage(ctx context.Context, client *elastic.Client, index string, chatID string, senderID string, text string) (*model.Message, error) {
    m := &model.Message{
        ChatID:    chatID,
        SenderID:  senderID,
        Text:      &text,
        Timestamp: time.Now(),
    }

    s, err := utils.ParseToString(m)

    if err != nil {
        return nil, err
    }

    _, err = client.Index().
        Index(index).
        BodyString(s).
        Do(ctx)

    if err != nil {
        fmt.Println("Error Storing the Text Message")
        return nil, err
    }
    return m, nil
}

Now, how can I mock this or even test this? I have seen a lot of examples but I am not sure of a good approach.

Aucun commentaire:

Enregistrer un commentaire