dousou1878 2018-10-12 14:40
浏览 31

导出Golang软件包进行测试?

In trying to come with test against code that uses the following struct:

type DatabaseSt struct {
    DBName            string
    DBConnectionStr   string
    dbConnection      *sql.DB
    InterpolateParams bool

    //Archived Databases
    MinFinancialYear int
    MaxFinancialYear int
}

//DatabaseContext The context to use if the use of a database is needed.
type DatabaseContext struct {
    *Context
    Database DatabaseSt
}

I stumbled upon this Medium article claiming that you can export Golang packages, with their internals, in test code. Unfortunately, I'm not sure what they mean in their last words:

export_test.go only be include when we run go test, so it not pollute your API, and user never access them(not like java’s @VisibleForTesting), and it build a bridge let unexported one accessible in math_test

and even worse, replication of it leads to nowhere fast:

enter image description here

/* Here, context is the package containing the struct I want full access to */

I basically need to be able to set the dbConnection of that DatabaseSt for testing, without modifying the source code.

  • 写回答

1条回答 默认 最新

  • dongxuanjiao0795 2018-10-12 15:40
    关注

    Add the following file named export_test.go:

    package context
    
    func SetDbConnection(DatabaseSt *ds, db *sql.DB) {
        ds.dbConnection = db
    }
    

    Use it from other test files in the same directory like this:

    package context_test
    
    import "context"
    
    func FooTest(t *testing.T) {
         ...
         context.SetDbConnection(ds, db)
         ...
    }
    

    Alternatively, write the test in the context package so you have full access to the members:

    package context
    
    func FooTest(t *testing.T) {
         ...
         ds.dbConnection = db
         ...
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入