Leave a Comment
Mocking for testing go code
If you’re testing go code and have a huge API you have to mock, you have two options:
make your dummy struct with embedded interface and implement only methods you need, or
use your own interface that has only methods you need (and change your code to use that).
For instance, I had amazon’s s3 API, which is about 100 methods long, and I only needed two of them (for instance).
So, I declare my own interface and have couple of structs, see code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
type S3CompatibleStorage interface { DeleteObject(*s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) GetObject(*s3.GetObjectInput) (*s3.GetObjectOutput, error) } // -- implementation func NewDummyS3CompatibleStorage() *DummyS3CompatibleStorage { return &DummyS3CompatibleStorage{} } type DummyS3CompatibleStorage struct{} func (d *DummyS3CompatibleStorage) DeleteObject(input *s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) { return &s3.DeleteObjectOutput{}, nil } func (d *DummyS3CompatibleStorage) GetObject(input *s3.GetObjectInput) (*s3.GetObjectOutput, error) { return &s3.GetObjectOutput{}, nil } // --another implementation for failing one of the methods type DummyS3WithDeleteObjectFail struct { *DummyS3CompatibleStorage } func (d *DummyS3WithPutObjectWithContextFail) DeleteObject(*s3.DeleteObjectInput, ...request.Option) (*s3.DeleteObjectOutput, error) { return nil, errors.New("you wanted DeleteObjectOutput to fail") } |
If you want to generate mocks, you can use these two libraries:
mockery
minimock
Similar Posts
- None Found
LEAVE A COMMENT
Для отправки комментария вам необходимо авторизоваться.