DATA-DOG / go-sqlmock

Sql mock driver for golang to test database interactions
Other
6.05k stars 406 forks source link

sqlmock with GORM return empty #226

Open sandrich opened 4 years ago

sandrich commented 4 years ago

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 commented 4 years ago

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