1 回答

TA貢獻1735條經驗 獲得超5個贊
您可以做幾件事。
簡單的方法
如果你想保持簡單,你可以做的是讓你的模擬結構具有它應該返回的字段,并且在每個測試用例中你將這些字段設置為你的模擬應該為該測試用例返回的內容。
這樣,您可以以不同的方式使模擬成功或失敗。
此外,您不需要dbMock接口,因為dbConnMock實現了db接口,這就是您所需要的。
這是您的模擬的樣子:
type dbConnMock struct {
FileCalled string
connStr string
err error
}
func (dbm dbConnMock) getConnectionStringFromConfig(file string) (connStr string, err error) {
dbm.FileCalled = file
return dbm.connStr, dbm.err
}
現在,您可以通過使用驗證您的方法是否使用預期參數調用FileCalled,并且可以使其具有您想要模擬的行為。
如果你還想確保你的方法只被調用一次,你還可以添加一個計數器來查看它被調用了多少次。
使用模擬庫
如果您不想擔心編寫該邏輯,一些庫可以為您完成,例如testify/mock。
這是一個簡單的模擬如何使用的示例testify/mock:
type dbMock struct {
mock.Mock
}
func (m *dbMock) getConnectionStringFromConfig(file string) (string, error) {
args := m.Called(file)
return args.String(0), args.Error(1)
}
func TestSomething(t *testing.T) {
tests := []struct {
description string
connStr string
err error
expectedFileName string
// add expected outputs and inputs of your tested function
}{
{
description: "passing test",
connStr: "valid connection string",
err: nil,
expectedFileName: "valid.json",
},
{
description: "invalid file",
connStr: "",
err: errors.New("invalid file"),
expectedFileName: "invalid.json",
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
dbMock := &dbConnectionMock{}
dbMock.
On("getConnectionStringFromConfig", test.expectedFileName).
Return(test.connStr, test.err).
Once()
thing := &Something{
db: dbMock,
}
output, err := thing.doSomething()
// assert that output and err are expected
dbMock.AssertExpectations(t) // this will make sure that your mock is only used as expected in your test, depending on your `On` calls
})
}
}
此代碼確保您的方法被調用一次并使用特定參數,并將使其返回測試用例中指定的內容。
- 1 回答
- 0 關注
- 148 瀏覽
添加回答
舉報