Go 的第三天,如果这是一个新问题,请原谅 ;)。我正在创建一个简单的计算器,最终将有许多不同的任务:加法、减法、乘法等等……每个任务都有 2 个函数:第一个和第二个。
package main
import (
"github.com/mytestproj/calculator"
)
type Calc interface {
First(x int) int
Second(x int) int
}
func main() {
x := 16
var i Calc
a := calculator.Add{}
i = a
i.First(x)
i.Second(x)
}
我目前将所有内容组织为:
github.com/
mytestproj/
calculator/
addition.go
addition_test.go
subtraction.go
subtraction_test.go
main/
main.go
此外.go我还有:
package calculator
type Add struct{}
func BasicAddition(x int) int { // this won't be in the final release
return x + 2
}
func (h Add) First(x int) int {
x += 5
return x
}
func (h Add) Second(x int) int {
x += 10
return x
}
此外_test.go 我还有:
package calculator
import "testing"
func TestBasicAddition(t *testing.T) {
x := 30
if y := BasicAddition(x); y != 32 {
t.Errorf("Mine is %v", y)
}
}
func TestFirst(t *testing.T) {
x := 10
if y := First(x); y != 15 {
t.Errorf("First is %v", y)
}
}
当我运行测试时出现错误:
# github.com/mytestproj/calculator
./addition_test.go:15: undefined: First
FAIL github.com/mytestproj/calculator [build failed]
我的问题:如何测试“First?”
如果我完全删除 First 的测试,那么测试运行良好并且通过。
第二个问题:这个想法是构建一个具有许多不同功能的计算器应用程序。如果有更好的方法来组织代码,请告诉我。
最佳答案
First
是 Add
类型的方法。例如,
a := Add{}
a.First(x)
addition.go
package calculator
type Add struct{}
func BasicAddition(x int) int { // this won't be in the final release
return x + 2
}
func (h Add) First(x int) int {
x += 5
return x
}
func (h Add) Second(x int) int {
x += 10
return x
}
addition_test.go
package calculator
import "testing"
func TestBasicAddition(t *testing.T) {
x := 30
if y := BasicAddition(x); y != 32 {
t.Errorf("Mine is %v", y)
}
}
func TestFirst(t *testing.T) {
x := 10
a := Add{}
if y := a.First(x); y != 15 {
t.Errorf("First is %v", y)
}
}
输出:
$ go test -v
=== RUN TestBasicAddition
--- PASS: TestBasicAddition (0.00s)
=== RUN TestFirst
--- PASS: TestFirst (0.00s)
PASS
ok so/calculator 0.002s
$
关于unit-testing - 如何测试我的接口(interface)功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26370976/