wallet: check withdraw border cases

This commit is contained in:
vinchent 2024-09-11 11:26:39 +02:00
parent 8ed0235074
commit f6b17eaff3
2 changed files with 22 additions and 2 deletions

View File

@ -1,6 +1,9 @@
package wallet package wallet
import "fmt" import (
"errors"
"fmt"
)
type Bitcoin int type Bitcoin int
@ -16,8 +19,12 @@ func (w *Wallet) Deposit(amount Bitcoin) {
w.balance += amount w.balance += amount
} }
func (w *Wallet) Withdraw(amount Bitcoin) { func (w *Wallet) Withdraw(amount Bitcoin) error {
if w.balance < amount {
return errors.New("not enough to withdraw")
}
w.balance -= amount w.balance -= amount
return nil
} }
func (w *Wallet) Balance() Bitcoin { func (w *Wallet) Balance() Bitcoin {

View File

@ -11,14 +11,27 @@ func TestWallet(t *testing.T) {
t.Errorf("got %q want %q", got, want) t.Errorf("got %q want %q", got, want)
} }
} }
t.Run("deposit", func(t *testing.T) { t.Run("deposit", func(t *testing.T) {
wallet := Wallet{} wallet := Wallet{}
wallet.Deposit(10) wallet.Deposit(10)
assertBalance(t, wallet, Bitcoin(10)) assertBalance(t, wallet, Bitcoin(10))
}) })
t.Run("withdraw", func(t *testing.T) { t.Run("withdraw", func(t *testing.T) {
wallet := Wallet{balance: Bitcoin(20)} wallet := Wallet{balance: Bitcoin(20)}
wallet.Withdraw(10) wallet.Withdraw(10)
assertBalance(t, wallet, Bitcoin(10)) assertBalance(t, wallet, Bitcoin(10))
}) })
t.Run("withdraw insufficient funds", func(t *testing.T) {
startingBalance := Bitcoin(20)
wallet := Wallet{balance: startingBalance}
err := wallet.Withdraw(100)
assertBalance(t, wallet, startingBalance)
if err == nil {
t.Error("wanted an error but didn't get one")
}
})
} }