1 回答

TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以做幾件事。
簡(jiǎn)單的方法
如果你想保持簡(jiǎn)單,你可以做的是讓你的模擬結(jié)構(gòu)具有它應(yīng)該返回的字段,并且在每個(gè)測(cè)試用例中你將這些字段設(shè)置為你的模擬應(yīng)該為該測(cè)試用例返回的內(nèi)容。
這樣,您可以以不同的方式使模擬成功或失敗。
此外,您不需要dbMock接口,因?yàn)閐bConnMock實(shí)現(xiàn)了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
}
現(xiàn)在,您可以通過使用驗(yàn)證您的方法是否使用預(yù)期參數(shù)調(diào)用FileCalled,并且可以使其具有您想要模擬的行為。
如果你還想確保你的方法只被調(diào)用一次,你還可以添加一個(gè)計(jì)數(shù)器來查看它被調(diào)用了多少次。
使用模擬庫(kù)
如果您不想擔(dān)心編寫該邏輯,一些庫(kù)可以為您完成,例如testify/mock。
這是一個(gè)簡(jiǎn)單的模擬如何使用的示例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
})
}
}
此代碼確保您的方法被調(diào)用一次并使用特定參數(shù),并將使其返回測(cè)試用例中指定的內(nèi)容。
- 1 回答
- 0 關(guān)注
- 146 瀏覽
添加回答
舉報(bào)