計算機科学のブログ

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

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

コード

sample_test.go

package sample

import "testing"

func TestEmpty(t *testing.T) {
	empty := newRectangle(0, 0, 0, 0)
	if !empty.isEmpty() {
		t.Errorf("%v.isEmpty() is not true", empty)
	}
}

func TestWidth(t *testing.T) {
	empty := newRectangle(0, 0, 0, 0)
	got := empty.getWidth()
	want := 0.0
	if got != want {
		t.Errorf("%v.getWidth() got %v, want %v", empty, got, want)
	}
}

func TestRate(t *testing.T) {
	exchange := newExchange()
	exchange.addRate("USD", "GBP", 2)
	got, _ := exchange.findRate("USD", "GBP")
	want := 2
	if got != want {
		t.Errorf("%v.findRate(USD, GBP) got %v, want %v", exchange, got, want)
	}
	_, err := exchange.findRate("USD", "AAA")
	if err == nil {
		t.Errorf("%v.findRate(USD, AAA) got %v, want error",
			exchange, err)
	}
}

sample.go

package sample

import (
	"errors"
	"math"
)

type rectangle struct {
	x1, y1, x2, y2 float64
}

func newRectangle(x1, y1, x2, y2 float64) rectangle {
	return rectangle{}
}
func (r rectangle) isEmpty() bool {
	return true
}
func (r rectangle) getWidth() float64 {
	return math.Abs(r.x1 - r.x2)
}

type exchange struct{}

func newExchange() *exchange {
	return &exchange{}
}

func (ex *exchange) addRate(from, to string, rate int) {}

// func (ex *exchange) findRate(from, to string) int {
func (ex *exchange) findRate(from, to string) (int, error) {
	// return 2
	// return 2, nil
	if to == "GBP" {
		return 2, nil
	}
	return 0, errors.New("error")
}

入出力結果(Terminal, Zsh)

% go test
PASS
ok  	_/.../sample	0.399s
% go test
PASS
ok  	_/.../sample	0.295s
% go test
PASS
ok  	_/.../sample	0.313s
% go test
--- FAIL: TestRate (0.00s)
    sample_test.go:31: &{}.findRate(USD, AAA) got <nil>, want error
FAIL
exit status 1
FAIL	_/.../sample	0.284s
% go test
PASS
ok  	_/.../sample	0.279s
%