You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GoConvey自定义断言不符合预期,编译错误排查求助

解决GoConvey自定义断言无法正常工作的问题

看起来你踩了GoConvey自定义断言的一个常见坑——函数签名不符合框架要求,哪怕你不需要传入预期值,也得遵循它的规范来写,不然编译器或者框架本身会识别不了你的断言函数。

先看你给出的代码片段,你把函数改成了单参数的shouldBeInTheLast24Hours(targetDate time.Time) string,但GoConvey要求自定义断言函数必须遵循以下签名:

func(actual interface{}, expected ...interface{}) string

空字符串表示断言通过,非空字符串则是断言失败时的错误提示。

接下来给你一个完整的可运行实现:

import (
    "time"
    "github.com/smartystreets/goconvey/convey"
)

func shouldBeInTheLast24Hours(actual interface{}, expected ...interface{}) string {
    // 先把实际值转换成time.Time类型,处理类型不匹配的情况
    targetDate, ok := actual.(time.Time)
    if !ok {
        return "Expected value to be a time.Time instance"
    }

    // 计算24小时前的时间点
    twentyFourHoursAgo := time.Now().Add(-24 * time.Hour)

    // 判断目标时间是否在过去24小时内
    if targetDate.After(twentyFourHoursAgo) && targetDate.Before(time.Now()) {
        return "" // 断言通过,返回空字符串
    }

    return "Target date is not within the last 24 hours"
}

然后在你的测试代码里这么用:

convey.Convey("Test something", t, func() {
    testDate := time.Now().Add(-12 * time.Hour) // 12小时前的时间,应该通过断言
    convey.So(testDate, shouldBeInTheLast24Hours)
})

另外要注意几个细节:

  • 一定要确保你的断言函数和测试代码在同一个包,或者被测试代码正确导入
  • 如果你的结构体字段是time.Time类型,直接把字段值传给So函数就行,比如convey.So(myStruct.CreatedAt, shouldBeInTheLast24Hours)
  • 如果你需要处理时区问题,可以把time.Now()换成time.Now().UTC()(或者你业务对应的时区),避免时区差异导致判断错误

内容的提问来源于stack exchange,提问作者TPPZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:19:46