Last active
July 10, 2018 20:18
-
-
Save vsobotka/96258b73246a12c817c642093d6803dd to your computer and use it in GitHub Desktop.
Test Driven Development in Go - https://medium.com/@pierreprinetti/test-driven-development-in-go-baeab5adb468
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
fmt.Printf("Hello, world.\n") | |
} | |
func factorsOf(n int) []int { | |
var factors []int | |
for divisor := 2; n > 1; divisor++ { | |
for n%divisor == 0 { | |
factors = append(factors, divisor) | |
n /= divisor | |
} | |
} | |
return factors | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"reflect" | |
"testing" | |
) | |
func TestFactorOf(t *testing.T) { | |
type checkFunc func([]int) error | |
isEmptyList := func(have []int) error { | |
if len(have) > 0 { | |
return fmt.Errorf("Expected empty list, found %v.", have) | |
} | |
return nil | |
} | |
is := func(want ...int) checkFunc { | |
return func(have []int) error { | |
if !reflect.DeepEqual(have, want) { | |
return fmt.Errorf("Expected list %v, found %v.", want, have) | |
} | |
return nil | |
} | |
} | |
tests := [...]struct { | |
in int | |
check checkFunc | |
}{ | |
{1, isEmptyList}, | |
{2, is(2)}, | |
{3, is(3)}, | |
{4, is(2, 2)}, | |
{5, is(5)}, | |
{6, is(2, 3)}, | |
{7, is(7)}, | |
{8, is(2, 2, 2)}, | |
{9, is(3, 3)}, | |
{2 * 2 * 3 * 3 * 5 * 7 * 11 * 11 * 13, is(2, 2, 3, 3, 5, 7, 11, 11, 13)}, | |
} | |
for _, tc := range tests { | |
t.Run(fmt.Sprintf("Factors of %d", tc.in), func(t *testing.T) { | |
factors := factorsOf(tc.in) | |
if err := tc.check(factors); err != nil { | |
t.Error(err) | |
} | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment