計算機科学のブログ

テスト駆動開発のパターン(Patterns for Test-Driven Development) テスティングのパターン(Testing Patterns)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅲ部(テスト駆動開発のパターン(Patterns for Tejst-Driven Development))、第27章(テスティングのパターン(Testing Patterns))をJava、PythonではなくGo言語で取り組んでみる。

コード

sample_test.go

package sample

import "testing"

func TestOrderLookup(t *testing.T) {
	db := newMockDatabase()
	db.expectQuery("SELECT order_no FROM Order WHERE cust_no = 123")
	db.returnResult([]string{"Order 2", "Order3"})
}

func TestNotification(t *testing.T) {
	result := newTestResult()
	listener := newResultListener()
	result.addListener(listener)
	listener.startTest()
	if listener.count != 1 {
		t.Errorf("%v.count is not 1", listener)
	}
}

func TestTemplateMethod(t *testing.T) {
	result := newTestResult()
	templateMethod(result)
	got := result.log
	want := "setUp testMethod tearDown "
	if got != want {
		t.Errorf("%v.log got '%v', want '%v'", result, got, want)
	}
}

func TestFileSystemError(t *testing.T) {
	_, err := createNewFile("foo")
	if err == nil {
		t.Errorf("%v is not errror", err)
	}
}

sample.go

package sample

import (
	"errors"
	"os"
)

type mockDatabase struct{}

func newMockDatabase() *mockDatabase {
	return &mockDatabase{}
}
func (db *mockDatabase) expectQuery(q string)           {}
func (db *mockDatabase) returnResult(strSlice []string) {}

type testResult struct {
	log string
}

func newTestResult() *testResult {
	return &testResult{}

}
func (tr *testResult) addListener(rl resultListener) {}
func (tr *testResult) setUp() {
	tr.log += "setUp "
}
func (tr *testResult) tearDown() {
	tr.log += "tearDown "
}

type resultListener struct {
	count int
}

func newResultListener() resultListener {
	return resultListener{}
}
func (rl *resultListener) startTest() {
	rl.count++
}
func templateMethod(r *testResult) {
	r.setUp()
	r.log += "testMethod "
	r.tearDown()
}

type fullFile os.File

func createNewFile(path string) (os.File, error) {
	return os.File{}, errors.New("IOError")
}

入出力結果(Terminal, Zsh)

% go test
--- FAIL: TestNotification (0.00s)
    sample_test.go:16: {0}.count is not 1
FAIL
exit status 1
FAIL	_/Users/.../sample	0.609s
% go test
--- FAIL: TestNotification (0.00s)
    sample_test.go:16: {0}.count is not 1
FAIL
exit status 1
FAIL	_/Users/.../sample	0.292s
% go test
PASS
ok  	_/Users/.../sample	0.224s
% go test
--- FAIL: TestTemplateMethod (0.00s)
    sample_test.go:27: &{}.log got '', want 'setUp testMethod tearDown '
FAIL
exit status 1
FAIL	_/Users/.../sample	0.287s
% go test
PASS
ok  	_/Users/.../sample	0.297s
% go test  
PASS
ok  	_/Users/.../sample	0.297s
%