GO表示自定义断言未按预期工作

GO表示自定义断言未按预期工作,go,tdd,goconvey,Go,Tdd,Goconvey,不确定为什么以下自定义断言不起作用,这似乎是一个编译错误,但我使用的语法似乎与他们的wiki页面中解释的一致: 我基本上想声明一个时间。结构中的time字段表示过去24小时内的一个日期 // func shouldBeInTheLast24Hours(targetDate time.Time, foo time.Time) string { func shouldBeInTheLast24Hours(targetDate time.Time) string { if targetDate

不确定为什么以下自定义断言不起作用,这似乎是一个编译错误,但我使用的语法似乎与他们的wiki页面中解释的一致:

我基本上想声明一个时间。结构中的time字段表示过去24小时内的一个日期

// func shouldBeInTheLast24Hours(targetDate time.Time, foo time.Time) string {
func shouldBeInTheLast24Hours(targetDate time.Time) string {
    if targetDate.Before(time.Now().Add(time.Duration(-24) * time.Hour)) {
        return ""
    } else {
        return "The target date is assumed to be in the last 24 hours, go *THERE* and fix stuff"
    }
}

type DateStuff struct {
    VipDate time.Time
}

func TestDateStuff(t *testing.T) {
    Convey("Given date stuff", t, func() {
        Convey("should verify some custom assertions are working", func() {
            myDateStruct := &DateStuff{VipDate: time.Now()}

            // So(myDateStruct.VipDate, shouldBeInTheLast24Hours, nil) // this throws "cannot use shouldBeInTheLast24Hours (type func(time.Time, time.Time) string) as type convey.assertion in argument to convey.So"
            So(myDateStruct.VipDate, shouldBeInTheLast24Hours) // this throws "cannot use shouldBeInTheLast24Hours (type func(time.Time) string) as type convey.assertion in argument to convey.So"
        })
    })
}
检查我使用的Go Transfer版本时,我看到:

$ cd $GOPATH/src/github.com/smartystreets/goconvey/ && git log -n 1 | grep Date
Date:   Fri Aug 25 16:14:26 2017 -0600
这是在2013年11月15日wiki页面上的日期之后,因此不应该在我的$GOPATH中更新Go Transfer库


我对这种闭包语法不太熟悉,但我似乎并没有误用它,但我看到了编译错误,所以我肯定遗漏了一些问题。

我将如何编写自定义断言:

func shouldBeInTheLast24Hours(actual interface{}, _ ...interface{}) string {
    providedDate := actual.(time.Time)
    theshold := time.Now().Add(time.Hour * -24)
    if providedDate.After(theshold) {
        return ""
    } else {
        return "The target date is assumed to be in the last 24 hours, go *THERE* and fix stuff"
    }
}

func TestDateStuff(t *testing.T) {
    Convey("Given date stuff", t, func() {
        Convey("should verify some custom assertions are working", func() {
            vipDate := time.Now()
            So(vipDate, shouldBeInTheLast24Hours)
        })
    })
}
自定义断言的函数签名必须与断言func类型匹配:

// assertion is an alias for a function with a signature that the convey.So()
// method can handle. Any future or custom assertions should conform to this
// method signature. The return value should be an empty string if the assertion
// passes and a well-formed failure message if not.
type assertion func(actual interface{}, expected ...interface{}) string
但是,正如评论中所述,已经定义了一个断言,可以满足您的需要:

So(vipDate, ShouldHappenWithin, time.Hour*24, time.Now())

在这个由Transfer提供的示例中,他们已经实现了您可能想要的功能,您不想使用它吗?您还收到了错误,因为您自定义的函数不是staisfy类型断言func,它是