diff --git a/learn_go_with_tests/pointers_errors/wallet.go b/learn_go_with_tests/pointers_errors/wallet.go index 0e7ddf2..d71514f 100644 --- a/learn_go_with_tests/pointers_errors/wallet.go +++ b/learn_go_with_tests/pointers_errors/wallet.go @@ -1,6 +1,9 @@ package pointers_errors -import "fmt" +import ( + "errors" + "fmt" +) type Stringer interface { String() string @@ -41,6 +44,10 @@ func (w *Wallet) Balance() Bitcoin { return (*w).balance } -func (w *Wallet) Withdraw(amount Bitcoin) { +func (w *Wallet) Withdraw(amount Bitcoin) error { + if amount > w.balance { + return errors.New("Withdraw operation failed. Insufficient funds") + } w.balance -= amount + return nil } diff --git a/learn_go_with_tests/pointers_errors/wallet_test.go b/learn_go_with_tests/pointers_errors/wallet_test.go index 230d4bc..08ede38 100644 --- a/learn_go_with_tests/pointers_errors/wallet_test.go +++ b/learn_go_with_tests/pointers_errors/wallet_test.go @@ -1,27 +1,26 @@ package pointers_errors import ( - "fmt" "testing" ) func TestWallet(t *testing.T) { - t.Run("deposit", func(t *testing.T) { - wallet := Wallet{} - - wallet.Deposit(10) - + assertBalance := func(t *testing.T, wallet Wallet, want Bitcoin) { + t.Helper() got := wallet.Balance() - // %p is placeholder for address in memory - fmt.Printf("address of balance in test is %p \n", &wallet.balance) - want := Bitcoin(10) - if got != want { - // t.Errorf("got %d want %d", got, want) t.Errorf("got %s want %s", got, want) } + } + + t.Run("deposit", func(t *testing.T) { + wallet := Wallet{} + + wallet.Deposit(10) + + assertBalance(t, wallet, Bitcoin(10)) }) t.Run("withdraw", func(t *testing.T) { @@ -29,11 +28,19 @@ func TestWallet(t *testing.T) { wallet.Withdraw(Bitcoin(10)) - got := wallet.Balance() - want := Bitcoin(10) + assertBalance(t, wallet, Bitcoin(10)) - if got != want { - t.Errorf("got %s want %s", got, want) + }) + + t.Run("withdraw insufficient funds", func(t *testing.T) { + startingBalance := Bitcoin(20) + wallet := Wallet{balance: startingBalance} + err := wallet.Withdraw(Bitcoin(100)) + + assertBalance(t, wallet, startingBalance) + + if err == nil { + t.Error("Wanted an error but didn't get one") } })