Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unit test duplicate key SQLSTATE: 23505 error #278

Open
Tak1za opened this issue Nov 15, 2021 · 0 comments
Open

Unit test duplicate key SQLSTATE: 23505 error #278

Tak1za opened this issue Nov 15, 2021 · 0 comments

Comments

@Tak1za
Copy link

Tak1za commented Nov 15, 2021

I'm trying to unit test a scenario where I get a duplicate key error but am not able to do the same.

service.go

func (s *service) addNewUser(newUser *models.User) error {
	newUser.ID = uuid.NewV4().String()
	if err := s.db.Client.Create(newUser).Error; err != nil {
		log.Println("error creating new user: ", err.Error())
		if pgError, ok := err.(*pgconn.PgError); ok {
			if pgError.Code == "23505" {
				errMessage := "user with the same email already exists"
				return errors.New(errMessage)
			}
			return errors.New(pgError.Message)
		}
		return err
	}

	return nil
}

service_test.go

func TestAddNewUser_Failure_DuplicateError(t *testing.T) {
	testDb, mock, _ := sqlmock.New()
	gormDB, _ := gorm.Open(postgres.New(postgres.Config{
		Conn: testDb,
	}))
	testNewUser := &models.User{
		Name:  "name",
		Email: "email",
	}

	mock.ExpectBegin()
	mock.ExpectExec(`INSERT INTO "users"`).WithArgs(
		AnyString{},
		AnyString{},
		AnyString{},
		AnyTime{},
		AnyTime{},
		nil).WillReturnError(&pgconn.PgError{
		Code: "23505",
	})
	mock.ExpectCommit()

	testService := &service{
		db: &db.Service{
			Client: gormDB,
		},
	}

	err := testService.addNewUser(testNewUser)
	assert.NotNil(t, err)
}

My unit test doesn't cover the lines:

if pgError.Code == "23505" {
    errMessage := "user with the same email already exists"
	return errors.New(errMessage)
}
return errors.New(pgError.Message)

Can someone help me understand why?
Basically the conversion of err to pgconn.PGError does not work in the unit test, but it does work when I hit my service from the API layer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants