TDD/TDF with Golang

Photo by Chinmay Bhattar on Unsplash
  • Balance
  • Credit
  • Debit
go mod init
  • Write your test in file name *_test.go.
  • Test function should always be named as Test* .
  • Test function only takes 1 argument t *testing.B .
  • To run a subtest we can use t.Run
  • We can use t.Helper() to deg=fine helper function
  • To run test run below command
go test

PASS
ok github.com/abhishekamralkar/fooBarBank 0.001s
go test -cover

PASS
coverage: 25.0% of statements
ok github.com/abhishekamralkar/fooBarBank 0.001s
go test -coverprofile=coverage.out
PASS
coverage: 25.0% of statements
ok github.com/abhishekamralkar/fooBarBank 0.002s
go tool cover -html=coverage.out
  • Benchmark function name should start from Benchmark
  • It takes exactly 1 parameter *testing.B
  • When Benchmark function executed, it runs b.N times and measures how long it takes.
  • By default Benchmarks are run sequentially.
  • We can pass -bench=. flag to test to run benchmark
go test -bench=.
goos: linux
goarch: amd64
pkg: github.com/abhishekamralkar/fooBarBank
cpu: Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
BenchmarkCredit-4 666403558 1.768 ns/op
PASS
ok github.com/abhishekamralkar/fooBarBank 1.364s
  • Helper functions accept a testing.TB which is an interface that *testing.T and *testing.B both satisfy.
  • Helper functions cab be called from a test, or a benchmark
  • t.Helper() is needed to tell the test suite that this method is a helper.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store