Unit Test - Golang
Hamdi Ahmadi Muzakkiy
Outline
- TDD
- Why ?
- Interface{}
- Basic Example Unit Test
- Complex Example Unit Test
TDD
Test Driven Development
add test
watch test fail
coding
run test
refactor
Disadvantage
- Make Development Slower
WHY ?
-
Faster Code For Future
-
Faster To Debug Code
-
Make More Confident
-
Maintainable, Flexible, Easily Extensible
Interface{}
type Animal interface{
RunSpeed() int
}
type Tiger struct {
Name string
TailLength float64
Foot int
}
type Snake struct {
Name string
ColorSkin string
}
func (t Tiger) RunSpeed() int {
return 100
}
func (s Snake) RunSpeed() int {
return 20
}
Basic Example Unit Test
func Plus(a, b int) int {
return a + b
}
func TestPlus(t *testing.T) {
assert.Equal(t, 4, Plus(1, 3), "TestPlus Should be a + b")
}
Results
PASS
coverage: 38.9% of statements
ok github.com/hamdimuzakkiy/golang 0.003s
--- FAIL: TestPlus (0.00s)
Error Trace: utils_test.go:27
Error: Not equal:
expected: 8
received: 4
Messages: ReverseString
FAIL
coverage: 38.9% of statements
exit status 1
FAIL github.com/hamdimuzakkiy/golang 0.004s
Complex
func GetPerson(d DbInterfaceGet) Person {
q := ` SELECT
name,
age
FROM
PERSON
LIMIT 1
`
var p Person
d.Get(&p, q)
p.Age *= 10
return p
}
func DoSomethingWithInsert() {
s := sqlx.DB{}
GetPerson(&s)
}
1/2 * 3 =
1/2∗3=
1 ^2 /3 * a + c
12/3∗a+c
a ^ 20 / 4
a20/4
https://github.com/hamdimuzakkiy/unit-test-golang
Thank You
TDD
By hamdi ahmadi
TDD
- 381