PPysolate SpineREAD THE CODE · UNDERSTAND THE SYSTEM
课程与章节
源码索引 / CURRENT IMPLEMENTATION

learning/go-patterns/patterns/interfaces/interfaces_test.go

41 行 · 点击行号可定位;函数链接随声明位置更新,不手填行号。

跳到函数 / 声明
package interfaces

import (
	"testing"
)

type mapCatalog map[string]Product

func (m mapCatalog) Find(name string) (Product, bool) {
	product, ok := m[name]
	return product, ok
}

func TestPriceOfUsesTheSmallInterface(t *testing.T) {
	catalog := mapCatalog{"book": {Name: "book", PriceCents: 1299}}

	if got, ok := PriceOf(catalog, "book"); !ok || got != 1299 {
		t.Fatalf("PriceOf() = (%d, %t), want (1299, true)", got, ok)
	}
	if _, ok := PriceOf(catalog, "missing"); ok {
		t.Fatal("PriceOf() reported a missing product")
	}
}

func TestCatalogFuncAdaptsAFunctionToTheInterface(t *testing.T) {
	catalog := CatalogFunc(func(name string) (Product, bool) {
		return Product{Name: name, PriceCents: len(name) * 100}, name != ""
	})

	if got, ok := PriceOf(catalog, "go"); !ok || got != 200 {
		t.Fatalf("PriceOf() = (%d, %t), want (200, true)", got, ok)
	}
}

func TestTotalFailsWithoutPartialResult(t *testing.T) {
	catalog := mapCatalog{"book": {Name: "book", PriceCents: 1299}}

	if got, ok := Total(catalog, []string{"book", "missing"}); ok || got != 0 {
		t.Fatalf("Total() = (%d, %t), want (0, false)", got, ok)
	}
}