unit testing – can't mock function with output in parameter-ThrowExceptions

Exception or error:

I have following interface:

type Datastore interface {
    Get(key interface{}, castTo interface{}) error
}

As you can see, I have castTo as parameter instead of having it in return. The usage would be like

var user *User
err:= Get("123-456", &user)

So the type is passed into the function. The reason is that it has implementation as below:

func (ddb *DynamoDB) Get(key interface{}, castTo interface{}) error {

    ...

    return dynamodbattribute.UnmarshalMap(result.Item, &castTo)
}

In the implementation, it uses function from aws dynamodb SDK which is as follow:

Source code

func UnmarshalMap(m map[string]*dynamodb.AttributeValue, out interface{}) error {
    return NewDecoder().Decode(&dynamodb.AttributeValue{M: m}, out)
}

The interface becomes very generic. But the challenge I have right now is how to mock the interface. Because the Get interface is used by some other function for which I am writing unit tests.

func (r *repository) Get(id string) (*User, error) {
    var user *User
    if err := r.datastore.Get(id, &user); err != nil {
        return nil, err
    }

    ...

    return account, nil
}

During the unit tests, I need to mock the datastore.Get() to return some fake user and then compare with the expected user.

I am using conterfeiter to mock and it can only mock the return result.

Does anyone encounter similar problem or know how to solve this?

How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *