Categorygithub.com/zhashkevych/go-sqlxmock
modulepackage
1.5.1
Repository: https://github.com/zhashkevych/go-sqlxmock.git
Documentation: pkg.go.dev

# README

SQL driver mock for Golang (with jmoiron/sqlx support)

Forked from DATA-DOG/go-sqlmock

Added functionality

  • Newx() and NewxWithDNS() which returns *sqlx.DB object instead of *sql.DB

Install

https://github.com/zhashkevych/go-sqlxmock@master

Usage Example

Repository Implementation:

type UserRepository interface {
	Insert(user domain.User) (int, error)
	GetById(id int) (domain.User, error)
	Get(username, password string) (domain.User, error)
}


type UserRepository struct {
	db *sqlx.DB
}

func NewUserRepository(db *sqlx.DB) *UserRepository {
	return &UserRepository{db: db}
}

func (r *UserRepository) Insert(user domain.User) (int, error) {
	var id int
	row := r.db.QueryRow("INSERT INTO users (first_name, last_name, username, password) VALUES ($1, $2, $3, $4) RETURNING id",
		user.FirstName, user.LastName, user.Username, user.Password)
	if err := row.Scan(&id); err != nil {
		return 0, err
	}

	return id, nil
}

Unit Tests:

import (
	sqlxmock "github.com/zhashkevych/go-sqlxmock"
	"testing"
)

func TestUserRepository_Insert(t *testing.T) {
	db, mock, err := sqlxmock.Newx()
	if err != nil {
		t.Fatalf("an error '%s' was not expected when opening a stub database connection", err)
	}
	defer db.Close()

	s := NewUserRepository(db)

	tests := []struct {
		name    string
		s       repository.UserRepository
		user    domain.User
		mock    func()
		want    int
		wantErr bool
	}{
		{
			//When everything works as expected
			name: "OK",
			s:    s,
			user: domain.User{
				FirstName: "first_name",
				LastName:  "last_name",
				Username:  "username",
				Password:  "password",
			},
			mock: func() {
				rows := sqlxmock.NewRows([]string{"id"}).AddRow(1)
				mock.ExpectQuery("INSERT INTO users").WithArgs("first_name", "last_name", "username", "password").WillReturnRows(rows)
			},
			want: 1,
		},
		{
			name:  "Empty Fields",
			s:     s,
			user: domain.User{
				FirstName: "",
				LastName:  "",
				Username:  "username",
				Password:  "password",
			},
			mock: func() {
				rows := sqlxmock.NewRows([]string{"id"}) 
				mock.ExpectQuery("INSERT INTO users").WithArgs("first_name", "last_name", "username", "password").WillReturnRows(rows)
			},
			wantErr: true,
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			tt.mock()
			got, err := tt.s.Insert(tt.user)
			if (err != nil) != tt.wantErr {
				t.Errorf("Get() error new = %v, wantErr %v", err, tt.wantErr)
				return
			}
			if err == nil && got != tt.want {
				t.Errorf("Get() = %v, want %v", got, tt.want)
			}
		})
	}
}

# Packages

No description provided by the author

# Functions

AnyArg will return an Argument which can match any kind of arguments.
MonitorPingsOption determines whether calls to Ping on the driver should be observed and mocked.
New creates sqlmock database connection and a mock to manage expectations.
NewColumn returns a Column with specified name.
NewErrorResult creates a new sql driver Result which returns an error given for both interface methods.
NewResult creates a new sql driver Result for Exec based query mocks.
NewRows allows Rows to be created from a sql driver.Value slice or from the CSV string and to be used as sql driver.Rows.
NewRowsWithColumnDefinition return rows with columns metadata.
NewWithDSN creates sqlmock database connection with a specific DSN and a mock to manage expectations.
Newx creates sqlmock database connection of *sqlx.DB type and a mock to manage expectations.
NewxWithDSN creates sqlmock database connection of *sqlx.DB type with a specific DSN and a mock to manage expectations.
QueryMatcherOption allows to customize SQL query matcher and match SQL query strings in more sophisticated ways.
ValueConverterOption allows to create a sqlmock connection with a custom ValueConverter to support drivers with special data types.

# Variables

CSVColumnParser is a function which converts trimmed csv column string to a []byte representation.
ErrCancelled defines an error value, which can be expected in case of such cancellation error.
QueryMatcherEqual is the SQL query matcher which simply tries a case sensitive match of expected and actual SQL strings without whitespace.
QueryMatcherRegexp is the default SQL query matcher used by sqlmock.

# Structs

Column is a mocked column Metadata for rows.ColumnTypes().
ExpectedBegin is used to manage *sql.DB.Begin expectation returned by *Sqlmock.ExpectBegin.
ExpectedClose is used to manage *sql.DB.Close expectation returned by *Sqlmock.ExpectClose.
ExpectedCommit is used to manage *sql.Tx.Commit expectation returned by *Sqlmock.ExpectCommit.
ExpectedExec is used to manage *sql.DB.Exec, *sql.Tx.Exec or *sql.Stmt.Exec expectations.
ExpectedPing is used to manage *sql.DB.Ping expectations.
ExpectedPrepare is used to manage *sql.DB.Prepare or *sql.Tx.Prepare expectations.
ExpectedQuery is used to manage *sql.DB.Query, *dql.DB.QueryRow, *sql.Tx.Query, *sql.Tx.QueryRow, *sql.Stmt.Query or *sql.Stmt.QueryRow expectations.
ExpectedRollback is used to manage *sql.Tx.Rollback expectation returned by *Sqlmock.ExpectRollback.
Rows is a mocked collection of rows to return for Query result.

# Interfaces

Argument interface allows to match any argument in specific way when used with ExpectedQuery and ExpectedExec expectations.
QueryMatcher is an SQL query string matcher interface, which can be used to customize validation of SQL query strings.
Sqlmock interface for Go 1.8+.
Sqlmock interface serves to create expectations for any kind of database action in order to mock and test real database behavior.

# Type aliases

QueryMatcherFunc type is an adapter to allow the use of ordinary functions as QueryMatcher.