mardi 2 mars 2021

GORM Test Insert Query [ExpectedBegin => expecting database transaction Begin]

I am testing the insert query using the DATA Dog library. Spend the whole day to figure out

Here is a model

package main

type Students struct {
    Id   string `json:"id"`
    Name string `json:"name"`
}

func (s *Students) TableName() string {
    return "students"
}

Repository

package main

import (
    "database/sql"
    "github.com/jinzhu/gorm"
    "github.com/stretchr/testify/require"
    "github.com/stretchr/testify/suite"
    "gopkg.in/DATA-DOG/go-sqlmock.v1"
    "testing"
)

type Suite struct {
    suite.Suite
    DB   *gorm.DB
    mock sqlmock.Sqlmock

    repository StudentRepository
    student     *Students
}

func (s *Suite) SetupSuite() {
    var (
        db  *sql.DB
        err error
    )

    db, s.mock, err = sqlmock.New()
    require.NoError(s.T(), err)

    s.DB, err = gorm.Open("mysql", db)
    require.NoError(s.T(), err)

    s.DB.LogMode(true)

    s.repository = NewStudentRepository(s.DB)
}



func (s *Suite) AfterTest(_, _ string) {
    require.NoError(s.T(), s.mock.ExpectationsWereMet())
}

func TestInit(t *testing.T) {
    suite.Run(t, new(Suite))
}

func (s *Suite) Test_repository_Create() {
    var (
        id   = "1"
        name = "A"
    )
    s.mock.ExpectBegin()
    s.mock.ExpectQuery(
        "INSERT INTO `students` (`id`,`name`) VALUES (?,?)").
        WithArgs(id, name)
    s.mock.ExpectCommit()

    err := s.repository.Create(id, name)
    require.NoError(s.T(), err)
}

RepositoryTest

package main

import (
    "github.com/jinzhu/gorm"
)

type StudentRepo struct {
    DB *gorm.DB
}

type StudentRepository interface {
    Create( id string ,name string) error
}

func NewStudentRepository(db *gorm.DB) *StudentRepo {
    return &StudentRepo{
        DB: db,
    }
}

func (ctx *StudentRepo) Create(id string, name string) error {

    student:= &Students{
        Id: id,
        Name: name,
    }

    return ctx.DB.Create(student).Error
}

When I tried to run the test getting the following error

 Error:          Received unexpected error:
                                there is a remaining expectation which was not matched: ExpectedBegin => expecting database transaction Begin
                Test:           TestInit/Test_repository_Create

Aucun commentaire:

Enregistrer un commentaire