go-sqlmock icon indicating copy to clipboard operation
go-sqlmock copied to clipboard

sqlmock with GORM return empty

Open sandrich opened this issue 5 years ago • 1 comments
trafficstars

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.

sandrich avatar May 19 '20 07:05 sandrich

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

xzjs avatar Jun 02 '20 08:06 xzjs