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

sqlmock with GORM return empty #226

Open
sandrich opened this issue May 19, 2020 · 1 comment
Open

sqlmock with GORM return empty #226

sandrich opened this issue May 19, 2020 · 1 comment

Comments

@sandrich
Copy link

I am new to sqlmock and go and struggle with my unittest. The mock part seems to work but form my understanding, my method GetCave should return the row I added in the mock part? It is a GRPC implementation and I use buffconn in the unittest.

Getting the following error

(cave.go:19) 
[2020-05-17 17:00:48]  [0.10ms]  SELECT * FROM "caves"  WHERE "caves"."deleted_at" IS NULL AND ((title = 'Test Cave')) ORDER BY "caves"."id" ASC LIMIT 1  
[1 rows affected or returned ] 
&{{0 0001-01-01 00:00:00 +0000 UTC 0001-01-01 00:00:00 +0000 UTC <nil>}    0 0}
✔✘


Failures:

  * /pkg/api/executor_test.go 
  Line 218:
  Expected: 'Test Cave'
  Actual:   ''
  (Should be equal)
  goroutine 99 [running]:

This is my test

Convey("Returns cave if title is set and exists", func() {
			request := GetCaveRequest{Title: "Test Cave"}

			caveRow := sqlmock.NewRows([]string{"Title", "CountryName", "RegionName", "Latitude", "Longitude"}).
				AddRow("Test Cave", "CH", "Zurich", 0, 0)
			mock.ExpectQuery(regexp.QuoteMeta(`SELECT * FROM "caves" WHERE "caves"."deleted_at" IS NULL AND ((title = $1)) ORDER BY "caves"."id" ASC LIMIT 1`)).
				WithArgs(request.Title).
				WillReturnRows(caveRow)
			ret, err := client.GetCave(ctx, &request)
			So(err, ShouldBeNil)
			So(ret.Cave.Title, ShouldEqual, request.Title)
		})

My actual GetCave function

func (e *apiExecutor) GetCave(ctx context.Context, request *GetCaveRequest) (*GetCaveReply, error) {
	if request.Title == "" {
		return nil, status.Errorf(codes.InvalidArgument, "Cave title is empty")
	}

	// check if the cave is existed
	cave, err := e.handler.FindCaveByUK(request.Title)
	if err != nil {
		return nil, status.Errorf(codes.Internal, "Find cave: %v", err)
	}
	if cave == nil {
		return nil, status.Errorf(codes.NotFound, "Cave does not exist")
	}

	fmt.Println(cave)

	return &GetCaveReply{
		Cave: &Cave{
			Title:       cave.Title,
			CountryName: cave.CountryName,
			RegionName:  cave.RegionName,
			Longitude:   cave.Longitude,
			Latitude:    cave.Latitude,
		},
	}, nil
}

Any help is much appreciated. Thanks.

@xzjs
Copy link

xzjs commented Jun 2, 2020

you can do that
mock.ExpectQuery("content").WillReturnRows(sqlmock.NewRows([]string{"id"}))
without AddRow

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

No branches or pull requests

2 participants