Unit Testing with Mocking gocb couchbase


I am currently using the following couchbase package in GO project.


type DbRepository interface {
	Insert(item *entity.SampleEntity) error


cbConnStr = config.Viper.GetString(
cbBucket = config.Viper.GetString(

type CbRepository struct {
Cluster *gocb.Cluster
Bucket *gocb.Bucket

func NewCbRepository() *CbRepository {
logger.BootstrapLogger.Debug(“Entering Repository.NewCbRepository() …”)

cluster, err := gocb.Connect(cbConnStr)
if err != nil {
	Username: config.Viper.GetString("database.couchbase.username"),
	Password: config.Viper.GetString("database.couchbase.password"),

bucket, err := cluster.OpenBucket(cbBucket, "")
if err != nil {
return &CbRepository{
	Cluster: cluster,
	Bucket:  bucket,


func (r CbRepository) Insert(item entity.Favorite) error {
logger.Logger.Debug(“Entering CbRepository.Insert() …”)
_, err := r.Bucket.Insert(“DocumentName”, item, 0)
if err != nil {
switch err {
* Include -case gocb.Err**- to handle Couchbase error types here as required.
* Fallback to default if none match
case gocb.ErrTimeout:
return entity.ErrDatabaseFailure
case gocb.ErrKeyExists:
return entity.ErrItemExists
return entity.ErrDefault
return nil

Note: Repository can be more than one, say couchbase or AWS Documentdb. That why I have separate Implementation for repositoryCb

This couchbase package is not interface driven, so how do I mock the database request?
r.Bucket.Insert() —
r.Bucket.Upsert() etc

My program structure looks like this:

  1. Main > Handler > Service layer > repositoryCb>repository

Using mockGen,
I have mocked repository interface in service layer.
Mocked service layer in handler

My problem is how to mock the core CRUD operations like bucket.Insert(), bucket.Upsert(), bucket.Get() etc

Kindly share your thoughts.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.