計算機科学のブログ

xUnit(The xUnit Example) 失敗の扱い(Dealing with Failure)

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅱ部(xUnit(The xUnit Example))、第22章(失敗の扱い(Dealing with Failure))をPythonではなくGo言語で取り組んでみる。

コード

package main

import (
	"fmt"
)

type testResult struct {
	runCount, errCount int
}

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

type wasRun struct {
	log string
}

func newWasRun() *wasRun {
	return &wasRun{}
}
func (wr *wasRun) setUp() {
	wr.log = "setUp "
}
func (wr *wasRun) tearDown() {
	wr.log += "tearDown "
}
func (wr *wasRun) testMethod() {
	wr.log += "testMethod "
}
func (wr *wasRun) testResult() {
	wr.log += "testMethod "
}
func (wr *wasRun) runTestMethod() *testResult {
	result := newTestResult()
	result.started()
	wr.setUp()
	wr.testMethod()
	wr.tearDown()
	fmt.Println("runTestMethod result.summary: ", result.summary())
	return result
}
func (wr *wasRun) runTestResult() *testResult {
	result := newTestResult()
	result.started()
	wr.setUp()
	wr.testResult()
	wr.tearDown()
	fmt.Println("runTestResult result.summary: ", result.summary())
	return result
}
func (wr *wasRun) testTestMethod() {
	wr.runTestMethod()
	got := wr.log
	want := "setUp testMethod teardown"
	if got != want {
		fmt.Printf("testMethod: '%v' != %v", got, want)
	}
}
func (wr *wasRun) testTestResult() {
	result := wr.runTestResult()
	got := result.summary()
	want := "1 run, 0 failed"
	if got != want {
		fmt.Printf("%v.summary got '%v', want '%v'", result, got, want)
	}
}
func (wr *wasRun) testTestFailedResultFormatting() {

}

func main() {
	wr := newWasRun()
	wr.runTestMethod()
}

入出力結果(Terminal, Zsh)

% go run ./main.go
% go run ./main.go
runTestMethod result.summary:  1 run, 0 failed
%