Chapter 14 - Automated Testing
Exercise 1: Testing a Package
Here is code for an ordinals
package, with an Ordinal
function that converts the integer 1
to the string 1st
, 2
to 2nd
, and so on. We have intentionally left out the code that converts 3
to 3rd
, so that we have a case where tests should fail.
You can either create this file manually, or install it automatically with:
$ go get github.com/jaymcgavren/ordinals
$GOPATH/src/github.com/jaymcgavren/ordinals/ordinals.go
// Package ordinals converts integers to ordinal numbers.
// 1: 1st, 2: 2nd, and so on.
package ordinals
import "fmt"
// Ordinal accepts an integer and returns a string with
// that integer's ordinal form.
func Ordinal(number int) string {
lastDigit := number % 10
isInTeens := (number%100)/10 == 1
if isInTeens {
return fmt.Sprintf("%dth", number)
} else if lastDigit == 1 {
return fmt.Sprintf("%dst", number)
} else if lastDigit == 2 {
return fmt.Sprintf("%dnd", number)
} else {
return fmt.Sprintf("%dth", number)
}
}
Your goal is to create automated tests with the following expectations:
Ordinal Parameter | Expected Return Value |
---|---|
1 |
"1st" |
2 |
"2nd" |
3 |
"3rd" (this test should fail) |
4 |
"4th" |
11 |
"11th" |
21 |
"21st" |
For now, you can use a failure message of "didn't match expected value"
for every test.
Solution
$GOPATH/src/github.com/jaymcgavren/ordinals/ordinals_test.go
package ordinals
import "testing"
func TestOne(t *testing.T) {
if Ordinal(1) != "1st" {
t.Error("didn't match expected value")
}
}
func TestTwo(t *testing.T) {
if Ordinal(2) != "2nd" {
t.Error("didn't match expected value")
}
}
func TestThree(t *testing.T) {
if Ordinal(3) != "3rd" {
t.Error("didn't match expected value")
}
}
func TestFour(t *testing.T) {
if Ordinal(4) != "4th" {
t.Error("didn't match expected value")
}
}
func TestEleven(t *testing.T) {
if Ordinal(11) != "11th" {
t.Error("didn't match expected value")
}
}
func TestTwentyOne(t *testing.T) {
if Ordinal(21) != "21st" {
t.Error("didn't match expected value")
}
}
Output:
--- FAIL: TestThree (0.00s)
ordinals_test.go:19: didn't match expected value
FAIL
FAIL github.com/jaymcgavren/ordinals 0.006s