I'm trying to implement unit tests in Go for an existing service which uses a connection pool struct and a connection struct from an existing library (call these LibraryPool
and LibraryConnection
) to connect to an external service.
To use these, the service functions in the main code uses a unique, global instance of the pool, which has a GetConnection()
method, like this:
// Current Main Code
var pool LibraryPool // global, instantiated in main()
func someServiceFunction(w http.ResponseWriter, r *http.Request) {
// read request
// ...
conn := pool.GetConnection()
conn.Do("some command")
// write response
// ...
}
func main() {
pool := makePool() // builds and returns a LibraryPool
// sets up endpoints that use the service functions as handlers
// ...
}
I'd like to unit-test these service functions without connecting to the external service, and so I'd like to mock the LibraryPool and LibraryConnection. To allow for this, I was thinking of changing the main code to something like this:
// Tentative New Main Code
type poolInterface interface {
GetConnection() connInterface
}
type connInterface interface {
Do(command string)
}
var pool poolInterface
func someServiceFunction(w http.ResponseWriter, r *http.Request) {
// read request
// ...
conn := pool.GetConnection()
conn.Do("some command")
// write response
// ...
}
func main() {
pool := makePool() // still builds a LibraryPool
}
In the tests, I would use mock implementations MockPool
and MockConnection
of these interfaces, and the global pool
variable would be instantiated using MockPool
. I would instantiate this global pool
in a setup()
function, inside of a TestMain() function.
The problem is that in the new main code, LibraryPool
does not properly implement poolInterface
, because GetConnection()
returns a connInterface
instead of a LibraryConnection
(even though LibraryConnection
is a valid implementation of connInterface
).
What would be a good way to approach this kind of testing? The main code is flexible too, by the way.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…