Saving withdraw feature

drew/sql-it
Drew Bednar 8 months ago
parent 5d48c68b3f
commit 801dc1252c

@ -1,6 +1,9 @@
package pointers_errors package pointers_errors
import "fmt" import (
"errors"
"fmt"
)
type Stringer interface { type Stringer interface {
String() string String() string
@ -41,6 +44,10 @@ func (w *Wallet) Balance() Bitcoin {
return (*w).balance 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 w.balance -= amount
return nil
} }

@ -1,27 +1,26 @@
package pointers_errors package pointers_errors
import ( import (
"fmt"
"testing" "testing"
) )
func TestWallet(t *testing.T) { func TestWallet(t *testing.T) {
t.Run("deposit", func(t *testing.T) { assertBalance := func(t *testing.T, wallet Wallet, want Bitcoin) {
wallet := Wallet{} t.Helper()
wallet.Deposit(10)
got := wallet.Balance() 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 { if got != want {
// t.Errorf("got %d want %d", got, want)
t.Errorf("got %s want %s", 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) { t.Run("withdraw", func(t *testing.T) {
@ -29,11 +28,19 @@ func TestWallet(t *testing.T) {
wallet.Withdraw(Bitcoin(10)) wallet.Withdraw(Bitcoin(10))
got := wallet.Balance() assertBalance(t, wallet, Bitcoin(10))
want := 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")
} }
}) })

Loading…
Cancel
Save