应用依赖注入开展单元测试可提高可测试性和可扩展性。应用 wire 架构设定依存关系,定义接口并通过 newset 函数建立 injector。运用 newinvoker 函数检测依靠函数,并通过模拟依存关系认证函数正确与否启用并返回预期成果。
Go 框架中应用依赖注入开展单元测试
介绍
依赖注入是一种将依存关系传送给对象的软件开发方式。它允许你建立松散耦合代码,提升可测试性和可扩展性。在 Go 框架中应用依赖注入开展单元测试能使检测更方便、更可靠。
设定
为了应用依赖注入开展单元测试,需要用到一个依赖注入架构。建议使用 [wire](https://github.com/google/wire)。它是一个由 Google 研发的轻量、高性能的依赖注入架构。
应用 wire,首先要界定依存关系给予的接口:
type UserRepositoryinterface{
Get(idint)(User,error)
}
随后,能通过 wire.NewSet函数创建一个 Injector,该函数传到依赖项以及提供他们的函数:
funcInitializeUserRepository(dbsql.DB) UserRepository{
returnNewUserRepository(db)
}
var Injector wire.Injector
funcsetup(){
//应用 sqlmock 进行模拟
db, mock :=sqlmock.New()
deferdb.Close()
Injector= wire.NewSet(InitializeUserRepository, wire.Value(db), wire.Value(mock))
}
实战案例
假设有一个 GetUser 函数,它需要一个 UserRepository:
funcGetUser(idint)(User,error){
userRepo:= Injector.MustInstance(new(UserRepository)).(UserRepository)
returnuserRepo.Get(id)
}
要检测 GetUser 函数,可以用 wire 提供的 wire.NewInvoker函数,它接受 GetUser 函数及与依赖项做为参数:
funcTestGetUser(ttesting.T){
want:=&User{ID:1,Name:"John"}
setup()
mock.ExpectQuery("SELECT\FROMusersWHEREid=\?").WithArgs(1).WillReturnRows(
sqlmock.NewRows([]string{"id","name"}).AddRow(1,"John"),
)
got,err:= wire.NewInvoker(GetUser, Injector)(1)
iferr!=nil{
t.Fatalf("Unexpectederror:%v",err)
}
if!reflect.DeepEqual(got,want){
t.Errorf("Expecteduser%v,got%v",want,got)
}
}
在这个检测中,我们使用 sqlmock 模拟数据库交互。可以将期待的查询记录导入到 mock 中,我们能认证 GetUser 函数正确与否调用了存储库而且返回了预想的结论。
以上就是golang框架中怎么使用依赖注入开展单元测试的详细内容,大量请关注其他类似文章!