Skip to content

Instantly share code, notes, and snippets.

@davidaparicio
Created May 27, 2022 09:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidaparicio/9fa9e664b6eed47e054ee6de426abe1a to your computer and use it in GitHub Desktop.
Save davidaparicio/9fa9e664b6eed47e054ee6de426abe1a to your computer and use it in GitHub Desktop.
BDD in go, updated code from @zer0tonin / blog post https://alicegg.tech/2019/03/09/gobdd.html
Feature: bank account
A user's bank account must be able to withdraw and deposit cash
Moreover, as the user is rich, with a very large estate, and a lot of vast networking,
The bank tolerates having an overdrawn account, thank to expensive overdraft charges
Scenario Outline: Deposit
Given I have a bank account with <start>$
When I deposit <deposit>$
Then it should have a balance of <end>$
Examples:
| start | deposit | end |
| 10 | 0 | 10 |
| 10 | 10 | 20 |
| 100 | 50 | 150 |
| -100 | 50 | -50 |
Scenario Outline: Withdrawal
Given I have a bank account with <start>$
When I withdraw <withdrawal>$
Then it should have a balance of <end>$
Examples:
| start | withdrawal | end |
| 10 | 0 | 10 |
| 20 | 10 | 10 |
| 100 | 50 | 50 |
| 100 | 500 | -400 |
package bank
type account struct {
balance int
}
func (a *account) deposit(amount int) {
a.balance = a.balance + amount
}
func (a *account) withdraw(amount int) {
a.balance = a.balance - amount
}
package bank
import (
"fmt"
"github.com/cucumber/godog"
)
var testAccount *account
func iHaveABankAccountWith(balance int) error {
testAccount = &account{balance: balance}
return nil
}
func iDeposit(amount int) error {
testAccount.deposit(amount)
return nil
}
func iWithdraw(amount int) error {
testAccount.withdraw(amount)
return nil
}
func itShouldHaveABalanceOf(balance int) error {
if testAccount.balance == balance {
return nil
}
return fmt.Errorf("Incorrect account balance, I got %d, I wanted %d", testAccount.balance, balance)
}
func InitializeScenario(ctx *godog.ScenarioContext) {
// Add negative tests
ctx.Step(`^I have a bank account with (\-*\d+)\$$`, iHaveABankAccountWith)
ctx.Step(`^I deposit (\d+)\$$`, iDeposit)
ctx.Step(`^I withdraw (\d+)\$$`, iWithdraw)
ctx.Step(`^it should have a balance of (\-*\d+)\$$`, itShouldHaveABalanceOf)
}
module bank
go 1.18
require github.com/cucumber/godog v0.12.5
require (
github.com/cucumber/gherkin-go/v19 v19.0.3 // indirect
github.com/cucumber/messages-go/v16 v16.0.1 // indirect
github.com/gofrs/uuid v4.2.0+incompatible // indirect
github.com/hashicorp/go-immutable-radix v1.3.1 // indirect
github.com/hashicorp/go-memdb v1.3.3 // indirect
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/spf13/pflag v1.0.5 // indirect
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment