計算機科学のブログ

xUnit(The xUnit Example) 後片付け(Cleaning Up After) tearDown

テスト駆動開発 (Kent Beck(著)、和田 卓人(翻訳)、オーム社)の第Ⅱ部(xUnit(The xUnit Example))、第20章(後片付け(Cleaning Up After))をPythonではなくGo言語で取り組んでみる。

コード

package main

import (
	"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
}

// 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() {
	wr.setUp()
	wr.testMethod()
	wr.tearDown()
}
func testTestCase() {

}

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

}
func (wr *wasRun) testSetUp() {
	if wr.log != "setUp " {
		fmt.Fprintln(os.Stderr, "wr.log is not 'setUp '")
		os.Exit(1)
	}
}

func main() {
	testWasRun()
}

入出力結果(Terminal, Zsh)

% go run ./main.go
% go run ./main.go
after is not 1exit status 1
% go run ./main.go
after is not true
exit status 1
% go run ./main.go
after is not true
exit status 1
% go run ./main.go
setUp testMethodtestMethod tearDown  is not 'setUp testMethod tearDown
exit status 1
% go run ./main.go
%