使用界面功能。它可能需要对依赖项进行一些更改(在本例中为package2
)。
将您的代码更改为这样的内容(重点是定义多个接口以获得更好的可测试性):
type Fetcher interface {
FetchAllData() ([]Data, error)
}
type Saver interface {
SaveData([]Data) (int, error)
}
func CreateData(input package1.InputRequest) (output package1.OututResponse){
..some code
..some code
// when you are writing tests, replace it with `s := NewMocking()`
s := package2.NewStorage()
DBdata, err := s.FetchAllData() //function to fetch data from database
..some code
..some code
id, insertErr := s.SaveData(someData) //function to insert data
..some code
..some code
}
需要做一点改动package2
:
type MyStorage struct {}
func (s *MyStorage) FetchAllData ([]Data, error) {
// ... some fetching code
}
func (s *MyStorage) SaveData(someData []Data) (int, error) {
// ... some saving code
}
func NewStorage() *MyStorage {
// ... some initialization
}
当你想做一些不需要 的测试时package2
,定义你自己的模拟类型:
type Mocking struct {}
func (s *Mocking) FetchAllData ([]Data, error) {
// ... some mocking logic
}
func (s *Mocking) SaveData(someData []Data) (int, error) {
// ... some mocking logic
}
func NewMocking() *Mocking {
// ... initialize ...
}