gpt4 book ai didi

go - 如何在本地创建和使用我自己的 golang 包来运行此测试?

转载 作者:IT王子 更新时间:2023-10-29 01:59:29 25 4
gpt4 key购买 nike

我是 golang 的新手,正在完成编码练习,我在一个名为 leap 的目录中有以下所有文件。我正在使用 gvm 运行 golang 可执行文件(版本 1.4),使用诸如“go test leap_test.go”之类的命令。

当我执行 go test leap_test.go 时,我得到以下结果:

# command-line-arguments
leap_test.go:5:2: open /home/user/go/leap/leap: no such file or directory
FAIL command-line-arguments [setup failed]
  1. 如何包含 IsLeap() 函数以便测试正确运行。
  2. 为什么还要包含 cases_test.go?似乎 leap_test.go 就是测试所需的全部内容。

cases_test.go

package leap

// Source: exercism/x-common
// Commit: 945d08e Merge pull request #50 from soniakeys/master

var testCases = []struct {
year int
expected bool
description string
}{
{1996, true, "leap year"},
{1997, false, "non-leap year"},
{1998, false, "non-leap even year"},
{1900, false, "century"},
{2400, true, "fourth century"},
{2000, true, "Y2K"},
}

leap_test.go

package leap

import (
"testing"
"./leap"
)

var testCases = []struct {
year int
expected bool
description string
}{
{1996, true, "a vanilla leap year"},
{1997, false, "a normal year"},
{1900, false, "a century"},
{2400, true, "an exceptional century"},
}

func TestLeapYears(t *testing.T) {
for _, test := range testCases {
observed := IsLeap(test.year)
if observed != test.expected {
t.Fatalf("%v is %s", test.year, test.description)
}
}
}

leap.go

package leap

import(
"fmt"
)

func IsLeap(year int) bool {
return true
}

最佳答案

Command go

Test packages

Usage:

go test [-c] [-i] [build and test flags] [packages] [flags for test binary]

例如,

leap/leap.go

package leap

func IsLeap(year int) bool {
return true
}

leap/leap_test.go

package leap

import (
"testing"
)

var testCases = []struct {
year int
expected bool
description string
}{
{1996, true, "a vanilla leap year"},
{1997, false, "a normal year"},
{1900, false, "a century"},
{2400, true, "an exceptional century"},
}

func TestLeapYears(t *testing.T) {
for _, test := range testCases {
observed := IsLeap(test.year)
if observed != test.expected {
t.Fatalf("%v is %s", test.year, test.description)
}
}
}

如果 $GOPATH 设置为包含 leap 包目录:

$ go test leap
--- FAIL: TestLeapYears (0.00s)
leap_test.go:22: 1997 is a normal year
FAIL
FAIL leap 0.003s
$

或者,如果您cdleap 包目录:

$ go test
--- FAIL: TestLeapYears (0.00s)
leap_test.go:22: 1997 is a normal year
FAIL
exit status 1
FAIL so/leap 0.003s
$

关于go - 如何在本地创建和使用我自己的 golang 包来运行此测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29642985/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com