Skip to content

Instantly share code, notes, and snippets.

@joaoh82
Created June 5, 2019 17:48
Show Gist options
  • Save joaoh82/59fa3697a3e5c8056998e765c7b39bd6 to your computer and use it in GitHub Desktop.
Save joaoh82/59fa3697a3e5c8056998e765c7b39bd6 to your computer and use it in GitHub Desktop.
package main
import (
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
// bankAccount represents a bank account instance
type bankAccount struct {
// Private fields
id string
blocked bool
balance float64
}
// newBankAccount creates a new bank account instance
func newBankAccount(id string) (*bankAccount, error) {
if len(id) < 1 {
return nil, errors.New("invalid bank account id")
}
return &bankAccount{
id: id,
blocked: false,
balance: 0,
}, nil
}
func (ba *bankAccount) checkBlocked() error {
if ba.blocked {
return fmt.Errorf("account %s is blocked", ba.id)
}
return nil
}
// Balance returns the current balance of the account
func (ba *bankAccount) Balance() (float64, error) {
if err := ba.checkBlocked(); err != nil {
return 0, err
}
return ba.balance, nil
}
// Deposit deposits money onto the account
func (ba *bankAccount) Deposit(value float64) error {
if err := ba.checkBlocked(); err != nil {
return err
}
if value > 0 {
ba.balance += value
return nil
}
return fmt.Errorf("invalid deposit value: %f", value)
}
// Withdraw widthdraws money from the account
func (ba *bankAccount) Withdraw(value float64) error {
if err := ba.checkBlocked(); err != nil {
return err
}
if ba.balance-value < 0 {
return errors.New("insufficient funds")
}
ba.balance -= value
return nil
}
// TestDepositAndWithdrawal tests BankAccount.Deposit and BankAccount.Withdraw
func TestWithdrawal(t *testing.T) {
account, err := newBankAccount("ABC")
require.NoError(t, err)
require.NotNil(t, account)
b1, err := account.Balance()
require.NoError(t, err)
require.Equal(t, 0.0, b1)
require.NoError(t, account.Deposit(4.5))
b2, err := account.Balance()
require.NoError(t, err)
require.Equal(t, 4.5, b2)
require.NoError(t, account.Withdraw(2.5))
b3, err := account.Balance()
require.NoError(t, err)
require.Equal(t, 2.0, b3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment