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:
/* 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.
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
...
}