計算機科学のブログ

xUnit(The xUnit Example) 数え上げ(Counting)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅱ部(xUnit(The xUnit Example))、第21章(数え上げ(Counting))をPythonではなくGo言語で取り組んでみる。

コード

package main

import (
	"errors"
	"fmt"
	"os"
)

// TestCase ...
type TestCase struct {
	name string
}

// NewTestCase ...
func NewTestCase(name string) *TestCase {
	return &TestCase{name: name}
}

// WasRun ...
type wasRun struct {
	*TestCase
	wasRun bool
	log    string
}

type testResult struct {
	runCount int
}

func newTestResult() testResult {
	return testResult{runCount: 0}
}
func (tr *testResult) testStarted() {
	tr.runCount++
}
func (tr *testResult) summary() string {
	return fmt.Sprintf("%v run, 0 failed", tr.runCount)
}

// newWasRun ...
func newWasRun(name string) *wasRun {
	t := NewTestCase(name)
	return &wasRun{wasRun: false, TestCase: t}
}
func (wr *wasRun) setUp() {
	wr.log = "setUp "
}
func (wr *wasRun) tearDown() {
	wr.log += "tearDown "
}
func (wr *wasRun) testMethod() {
	wr.log += "testMethod "
}
func (wr *wasRun) run() testResult {
	result := newTestResult()
	result.testStarted()
	wr.setUp()
	wr.testMethod()
	wr.tearDown()
	return result
}
func (wr *wasRun) testBrokenMethod() error {
	return errors.New("Error")
}
func testTestCase() {

}

func testWasRun() {
	test := newWasRun("testMethod")
	test.run()
	if test.log != "setUp testMethod tearDown " {
		fmt.Fprintf(os.Stderr, "testWasRun: %v is not 'setUp testMethod tearDown\n", test.log)
		os.Exit(1)
	}

}
func (wr *wasRun) testSetUp() {
	if wr.log != "setUp " {
		fmt.Fprintln(os.Stderr, "testSetUp: wr.log is not 'setUp '")
		os.Exit(1)
	}
}
func (wr *wasRun) testResult() {
	test := newWasRun("testMethod")
	result := test.run()
	got := result.summary()
	want := "1 run, 0 failed"
	if got != want {
		fmt.Fprintf(os.Stderr, "testResult: %v.summary() got %v, want %v\n",
			test, got, want)
		os.Exit(1)
	}
}
func (wr *wasRun) testFailedResult() {
	test := newWasRun("testBrokenMethod")
	result := test.run()
	got := result.summary()
	want := "1 run, 1 failed"
	if got != want {
		fmt.Fprintf(os.Stderr, "testFailedResult: %v.summary() got %v, want %v\n",
			result, got, want)
		os.Exit(1)
	}
}

func main() {
	testWasRun()
	wr := newWasRun("testResult")
	wr.testResult()
}

入出力結果(Terminal, Zsh)

% go run ./main.go 
% go run ./main.go
% go run ./main.go
% go run ./main.go
% go run ./main.go
% go run ./main.go
% go run ./main.go
% go run ./main.go
&{0xc000010210 false setUp testMethod tearDown }.summary() got 2 run, 0 failed, want 1 run, 0 failedexit status 1
% go run ./main.go
testResult: &{0xc00008e1f0 false setUp testMethod tearDown }.summary() got 2 run, 0 failed, want 1 run, 0 failed
exit status 1
% go run ./main.go
%