diff --git a/doc/code.html b/doc/code.html index 5c60222aab..9072d0506b 100644 --- a/doc/code.html +++ b/doc/code.html @@ -203,3 +203,88 @@ Once your new code is tested and working, it's time to get it reviewed and submitted.

+

An example package with tests

+ +

+This example package, numbers, consists of the function +Double, which takes an int and returns that value +multiplied by 2. It consists of three files. +

+ +

+First, the package implementation, numbers.go: +

+ +
+package numbers
+
+func Double(i int) int {
+	return i * 2
+}
+
+ +

+Next, the tests, numbers_test.go: +

+ +
+package numbers
+
+import (
+	"testing"
+)
+
+type doubleTest struct {
+	in, out int
+}
+
+var doubleTests = []doubleTest{
+	doubleTest{1, 2},
+	doubleTest{2, 4},
+	doubleTest{-5, -10},
+}
+
+func TestDouble(t *testing.T) {
+	for _, dt := range doubleTests {
+		v := Double(dt.in)
+		if v != dt.out {
+			t.Errorf("Double(%d) returns %d; should be %d.", dt.in, v, dt.out)
+		}
+	}
+}
+
+ +

+Finally, the Makefile: +

+ +
+include $(GOROOT)/src/Make.$(GOARCH)
+
+TARG=numbers
+GOFILES=\
+	numbers.go\
+
+include $(GOROOT)/src/Make.pkg
+
+ +

+Running make install will build and install the package to +the $GOROOT/pkg/ directory (it can then be used by any +program on the system). +

+ +

+Running make test (or just running the command +gotest) will rebuild the package, including the +numbers_test.go file, and then run the TestDouble +function. The output "PASS" indicates that all tests passed +successfully. Breaking the implementation by changing the multiplier from +2 to 3 will allow you to see how failing tests are +reported. +

+ +

+See the gotest documentation and the +testing package for more detail. +