wallet: improve assertError again by creating a custom error type
This commit is contained in:
		@ -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
 | 
			
		||||
 | 
			
		||||
@ -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)
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user