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

时间:2015-04-15 06:26:07

标签: go

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

当我去测试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就是测试所需的全部内容。
  3. 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
    }
    

1 个答案:

答案 0 :(得分:3)

  

Command go

     

Test packages

     

用法:

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

例如,

<强>飞跃/ leap.go

package leap

func IsLeap(year int) bool {
    return true
}

<强>飞跃/ 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
$