首页  >  文章  >  后端开发  >  用于测试的 golang 接口

用于测试的 golang 接口

PHPz
PHPz转载
2024-02-09 09:57:15348浏览

用于测试的 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) 类型的值作为回调传递到 func(ctx context.context, name string) (e.response, error) 类型的值作为回调传递到 callimplementation 中,并完全摆脱该接口。或者,保留接口,定义类型,并使该类型成为当前 findsomethingindatabase 实现的接收者。然后,您可以将该类型传递给 callimplementation,因为它现在将实现 objectapi 中,并完全摆脱该接口。或者,保留接口,定义类型,并使该类型成为当前 findsomethingindatabase 实现的接收者。然后,您可以将该类型传递给

,因为它现在将实现 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在这种情况下,您可能希望将

的成员,而不是将其作为全局变量(现在看来就是这种情况)。🎜

以上是用于测试的 golang 接口的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除