-1

我想通过模拟其他包(package2)中的 FetchAllData() 和 SaveData() 来为 CreateData() 函数编写单元测试用例,请帮助我用示例模拟该函数,

提前致谢


func CreateData(input package1.InputRequest) (output package1.OututResponse){

    ..some code
    ..some code

    DBdata, err := package2.FetchAllData() //function to fetch data from database

    ..some code
    ..some code

    id, insertErr := package2.SaveData(someData) //function to insert data

    ..some code
    ..some code
}

我只需要模拟上面的函数而不修改函数。我在找那个

4

1 回答 1

2

使用界面功能。它可能需要对依赖项进行一些更改(在本例中为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 ...
}
于 2019-08-29T15:41:36.093 回答