From 20606d3ee59696a0e3e48b949777f9d83405b998 Mon Sep 17 00:00:00 2001 From: vinchent Date: Wed, 11 Sep 2024 11:35:52 +0200 Subject: [PATCH] wallet: improve assertError again by creating a custom error type --- wallet/wallet.go | 4 +++- wallet/wallet_test.go | 42 +++++++++++++++++++++--------------------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/wallet/wallet.go b/wallet/wallet.go index efa0bc4..056255a 100644 --- a/wallet/wallet.go +++ b/wallet/wallet.go @@ -7,6 +7,8 @@ import ( type Bitcoin int +var ErrInsufficientFunds = errors.New("cannot withdraw, insufficient funds") + func (b Bitcoin) String() string { return fmt.Sprintf("%d BTC", b) } @@ -21,7 +23,7 @@ func (w *Wallet) Deposit(amount Bitcoin) { func (w *Wallet) Withdraw(amount Bitcoin) error { if w.balance < amount { - return errors.New("not enough to withdraw") + return ErrInsufficientFunds } w.balance -= amount return nil diff --git a/wallet/wallet_test.go b/wallet/wallet_test.go index a0f7f89..79ccef5 100644 --- a/wallet/wallet_test.go +++ b/wallet/wallet_test.go @@ -3,26 +3,6 @@ package wallet import "testing" func TestWallet(t *testing.T) { - assertBalance := func(t testing.TB, wallet Wallet, want Bitcoin) { - t.Helper() - - got := wallet.Balance() - if got != want { - t.Errorf("got %q, want %q", got, want) - } - } - - assertError := func(t testing.TB, got error, want string) { - t.Helper() - - if got == nil { - t.Fatal("didn't get an error but wanted one") - } - if got.Error() != want { - t.Errorf("got %q, want %q", got, want) - } - } - t.Run("deposit", func(t *testing.T) { wallet := Wallet{} wallet.Deposit(10) @@ -40,7 +20,27 @@ func TestWallet(t *testing.T) { wallet := Wallet{balance: startingBalance} err := wallet.Withdraw(100) - assertError(t, err, "not enough to withdraw") + assertError(t, err, ErrInsufficientFunds) assertBalance(t, wallet, startingBalance) }) } + +func assertBalance(t testing.TB, wallet Wallet, want Bitcoin) { + t.Helper() + + got := wallet.Balance() + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} + +func assertError(t testing.TB, got error, want error) { + t.Helper() + + if got == nil { + t.Fatal("didn't get an error but wanted one") + } + if got != want { + t.Errorf("got %q, want %q", got, want) + } +}