AdSense

網頁

2021/7/14

Golang Testify mock 回傳自訂型態 return custom type

Go測試套件Testify mock回傳自訂型別的方式如下。


範例環境:

  • Go 1.16
  • Testify 1.7

使用Arguments.Get(index int) interface{}回傳可回傳任意型別。

例如下面為package model中自訂的struct Employee

model/employee.go

package model

type Employee struct {
    Id   int
    Name string
    Age  int
}

則在package service測試程式中使用Testiy的Get()設定回傳型態為model.Employee如下。

package serivce

import (
    "testing"

    "abc.com/demo/model"
    "github.com/stretchr/testify/mock"
)

// define mock type
type DependencyMock struct {
    mock.Mock
}

// use DependencyMock to implments a interface's method
func (depMock *DependencyMock) GetEmployee(...) model.Employee {
    args := depMock.Called(...)
    return args.Get(0).(model.Employee) // return custom type
}

func (depMock *DependencyMock) GetEmployees(...) []model.Employee {
    args := depMock.Called(...)
    return args.Get(0).([]model.Employee) // return slice of custom type
}

Get(0)0是指回傳參數的index值,上面GetEmployee()GetEmployees()只有一個回傳參數,所以index是0。


沒有留言:

AdSense