From d73528bd8b3bf57b3113df319d91040499ab8064 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vin=C3=ADcius=20Garcia?= Date: Wed, 3 Aug 2022 21:21:31 -0300 Subject: [PATCH] Add tests for the .Close() method --- internal_mocks.go | 9 +++++++++ ksql_test.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/internal_mocks.go b/internal_mocks.go index e022a92..2fae9b9 100644 --- a/internal_mocks.go +++ b/internal_mocks.go @@ -40,3 +40,12 @@ func (m mockTx) Rollback(ctx context.Context) error { func (m mockTx) Commit(ctx context.Context) error { return m.CommitFn(ctx) } + +// mockCloser mocks the io.Closer interface +type mockCloser struct { + CloseFn func() error +} + +func (m mockCloser) Close() error { + return m.CloseFn() +} diff --git a/ksql_test.go b/ksql_test.go index 1f3b579..a7c09d9 100644 --- a/ksql_test.go +++ b/ksql_test.go @@ -1,6 +1,8 @@ package ksql import ( + "fmt" + "io" "testing" tt "github.com/vingarcia/ksql/internal/testtools" @@ -38,3 +40,52 @@ func TestNewAdapterWith(t *testing.T) { tt.AssertNotEqual(t, err, nil) }) } + +func TestClose(t *testing.T) { + t.Run("should close the adapter if it implements the io.Closer interface", func(t *testing.T) { + c := DB{ + db: struct { + DBAdapter + io.Closer + }{ + DBAdapter: mockDBAdapter{}, + Closer: mockCloser{ + CloseFn: func() error { + return nil + }, + }, + }, + } + + err := c.Close() + tt.AssertNoErr(t, err) + }) + + t.Run("should exit normally if the adapter does not implement the io.Closer interface", func(t *testing.T) { + c := DB{ + db: mockDBAdapter{}, + } + + err := c.Close() + tt.AssertNoErr(t, err) + }) + + t.Run("should report an error if the adapter.Close() returns one", func(t *testing.T) { + c := DB{ + db: struct { + DBAdapter + io.Closer + }{ + DBAdapter: mockDBAdapter{}, + Closer: mockCloser{ + CloseFn: func() error { + return fmt.Errorf("fakeCloseErrMsg") + }, + }, + }, + } + + err := c.Close() + tt.AssertErrContains(t, err, "fakeCloseErrMsg") + }) +}