我正在写一个小的 POC 去上班,但我似乎无法弄清楚模拟技术。这是我到目前为止...
连接.go
package db
import (
"database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"strings"
_ "github.com/lib/pq"
)
type config map[string]interface{}
type DbConn struct {
db db
}
type db interface {
getConnectionStringFromConfig(file string) (connStr string, err error)
}
func NewDbConn(d db) *DbConn {
return &DbConn{db: d}
}
func getConnectionStringFromConfig(file string) (connStr string, err error) {
var c config
var bt []byte
if bt, err = ioutil.ReadFile(file); err != nil {
fmt.Printf("Error Reading config file: %v", err)
return
}
fmt.Println("Finish reading file. Going to construct a connection string")
if err = json.Unmarshal(bt, &c); err != nil {
fmt.Printf("Error unmarshalling config file: %v", err)
return
}
connStr = strings.TrimLeft(getConfigAsString(c), " ")
return
}
func getConfigAsString(c config) (connStr string) {
for k, v := range c {
connStr += strings.Join([]string{" " + k, v.(string)}, "=")
}
return
}
// Connect database connection
func (dbConn DbConn) Connect() (conn *sql.DB, err error) {
fmt.Println("Starting database connection...")
connStr, err := getConnectionStringFromConfig("path/to/conf.json")
if err != nil {
return
}
conn, err = sql.Open("some_driver", connStr)
return
}
连接测试.go
package db
import (
"errors"
"testing"
)
type dbConnMock struct {
db dbMock
}
type dbMock interface {
getConnectionStringFromConfig(file string) (connStr string, err error)
}
func (dbm dbConnMock) getConnectionStringFromConfig(file string) (connStr string, err error) {
return "", errors.New("123")
}
// should not throw error when trying to open db connection
func TestDatabaseConnection(t *testing.T) {
dbCon := &DbConn{}
_, err := dbCon.Connect()
if err != nil {
t.Errorf("test failed. \n %d", err)
}
}
如您所见,这是一个简单的数据库连接逻辑,我使用接口对其进行了测试和模拟。我想覆盖 100% 的代码,所以我必须模拟某些方法。上面的代码虽然有效,但第二个测试失败了,可能是因为我在尝试模拟它时遗漏了一些东西。请帮忙..
喵喔喔
相关分类