卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章34713本站已运行393

用于测试的 golang 接口

用于测试的 golang 接口

php小编草莓为您介绍一款用于测试的golang接口。在软件开发过程中,测试是不可或缺的环节,而这款接口则提供了便捷的测试功能。通过该接口,开发人员可以快速检验代码的正确性和稳定性,提高开发效率。无论是接口的功能测试、性能测试还是压力测试,该工具都能满足需求。此外,该接口还提供了简洁直观的测试结果展示,让开发人员能够更直观地了解代码的运行情况。无论您是初学者还是资深开发人员,这款golang接口都能为您的开发工作带来便利和效益。

问题内容

我试图在我的代码中创建一个数据库模拟,然后我向我的代码引入接口,以创建模拟:

这是我的代码(我不知道这是否是正确的方法)

package interfaces

type objectapi interface {
    findsomethingindatabase(ctx context.context, name string) (e.response, error)
}

我的接口实现是:

package repositories

func findsomethingindatabase(ctx context.context, name string) (e.response, error) {

    statement, err := db.sqlstatementwithctx(ctx,
        `select * 
         from table
         where name = ? limit 1`)

    row := statement.queryrowcontext(ctx, name)

    if err != nil {
        return e.response{}, err
    }

    statement.close()
    return toresponse(row), nil  //this method convert row database to e.response struct

}

现在我需要从一种方法调用 findsomethingindatabase 的实现,然后我收到一个对象类型接口:

func CallImplementation(request *dto.XRequest, repo i.ObjectAPI) dto.XResponse{
    result := repo.FindSomethingInDatabase(request.Ctx, request.Name)
// more code
}

但现在我不知道如何调用 callimplementation` 来传递带有实现的对象。

调用传递接口实现的方法

解决方法

接口描述类型。由于您的 findsomethingindatabase 实现只是一个没有接收器的 func,因此没有实现接口 objectapi 的类型。

您可以将 func(ctx context.context, name string) (e.response, error) 类型的值作为回调传递到 callimplementation 中,并完全摆脱该接口。或者,保留接口,定义类型,并使该类型成为当前 findsomethingindatabase 实现的接收者。然后,您可以将该类型传递给 callimplementation,因为它现在将实现 objectapi 接口。后者的一个示例(这将是我的可扩展性首选选项):

type database struct {}

func (d *database) FindSomethingInDatabase(ctx context.Context, name string) (e.Response, error) {
    // ...
}

func CallImplementation(request *dto.XRequest, repo i.ObjectAPI) dto.XResponse{
    result := repo.FindSomethingInDatabase(request.Ctx, request.Name)
// more code
}

func main() {
    db := &database{}
    _ = Callimplementation(getRequest(), db)
}

在这种情况下,您可能希望将 db 存储为 database 的成员,而不是将其作为全局变量(现在看来就是这种情况)。

卓越飞翔博客
上一篇: 如何匹配两次出现的相同但随机的字符串之间的字符
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏