mockを使ってのテストは主に「起こしにくいエラーを再現する」場合にのみ使っている。
gomockにて、「N回目呼ばれたらエラーを返す(それ以外は実際の処理が実行される)」モックの用意の仕方をメモする。
スタブを使う。
github.com
ctrl := gomock.NewController(t) defer ctrl.Finish() // 商品リポジトリのモック作成 productRep := mock_interfaces.NewMockIProductRepository(ctrl) callCount := 0 // カウンタを用意する productRep.EXPECT().GetById(gomock.Any(), gomock.Any()).DoAndReturn(func(id int, executor gorp.SqlExecutor) (*entities.ProductEntity, error) { callCount += 1 if callCount == 3 { // 3回目にエラーを発生させる return nil, errors.New("Productデータの取得に失敗しました") } else { // それ以外は本物で実際に処理を行う rep := repositories.NewProductRepository() return rep.GetById(id, executor) } }).AnyTimes()