diff options
| author | mihna123 <mihailonvojinovic@gmail.com> | 2026-08-23 17:47:16 +0200 |
|---|---|---|
| committer | mihna123 <mihailonvojinovic@gmail.com> | 2026-08-23 17:47:16 +0200 |
| commit | 1e43f2a59bba0462494066767fac140601791718 (patch) | |
| tree | 45a4d0c4f3159f4acd7949eebbbfe138e4c1bc3f /internal/listing/service_test.go | |
| parent | 516ed55e09a253255e7056d31eb59acfd68db3a8 (diff) | |
| download | openstore-1e43f2a59bba0462494066767fac140601791718.tar.gz openstore-1e43f2a59bba0462494066767fac140601791718.zip | |
listing: implement a service layer stub along with tests
Diffstat (limited to 'internal/listing/service_test.go')
| -rw-r--r-- | internal/listing/service_test.go | 89 |
1 files changed, 89 insertions, 0 deletions
diff --git a/internal/listing/service_test.go b/internal/listing/service_test.go new file mode 100644 index 0000000..1d555c9 --- /dev/null +++ b/internal/listing/service_test.go @@ -0,0 +1,89 @@ +package listing + +import ( + "errors" + "log/slog" + "os" + "slices" + "testing" +) + +func TestMain(m *testing.M) { + slog.SetDefault(slog.New(slog.DiscardHandler)) + os.Exit(m.Run()) +} + +func TestGetAll(t *testing.T) { + mock := NewRepositoryMock() + s := New(mock) + listings, err := s.GetAll() + if err != nil { + t.Error(err.Error()) + } + + if len(listings) != 3 { + t.Errorf("Listings lengths don't match. Have %d, want 3", + len(listings)) + } +} + +func TestGetAllWithError(t *testing.T) { + mock := &RepositoryMock{err: errors.New("db exploded")} + s := New(mock) + listings, err := s.GetAll() + + if err == nil { + t.Error("No error returned from faulty GetAll call") + } + + if listings != nil { + t.Error("Listings not nil when returned from faulty GetAll call") + } +} + +func TestGetByCategory(t *testing.T) { + mock := NewRepositoryMock() + s := New(mock) + + listings, err := s.GetByCategory("audi") + if err != nil { + t.Error(err.Error()) + } + + if len(listings) != 1 { + t.Errorf("Listings by category have wrong length. Have %d, want %d", + len(listings), 1) + } + if !slices.Contains(listings[0].category, "audi") { + t.Errorf("Returned listing has wrong category. Have %s, want audi", + listings[0].category) + } +} + +func TestGetByCategoryNoMatches(t *testing.T) { + mock := &RepositoryMock{} + s := New(mock) + + listings, err := s.GetByCategory("nonexistantcategory") + if err != nil { + t.Error(err.Error()) + } + + if listings != nil { + t.Error("Listings should be nil if no category matches") + } +} + +func TestGetByCategoryWithError(t *testing.T) { + mock := &RepositoryMock{err: errors.New("datacenter hit by asteroid")} + s := New(mock) + + listings, err := s.GetByCategory("mercedes") + if err == nil { + t.Error("Error nil when GetByCategory failed") + } + + if listings != nil { + t.Error("Listings not nil when GetByCategory failed") + } +} |
