duanlei5339 2018-03-29 02:54
浏览 87
已采纳

在golang中从另一个内部调用的模拟函数

I am trying to stub os.Stat and ioutil.ReadFile(path) as used the code below or if you like here on go playground [1]

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
)

func AssignFileValueFrom(path string, val *string) {
    var (
        tempValue []byte
        err       error
    )

    if _, err = os.Stat(path); err == nil {
        if err != nil {
            fmt.Println("There was a os stat error:", err)
        }

        tempValue, err = ioutil.ReadFile(path)
        if err != nil {
            fmt.Println("There was an io read error:", err)
        }
        *val = strings.TrimSpace(string(tempValue))
    }
}

I have used testify and tried following the example here [2]

package main

import (
    "testing"

    "github.com/stretchr/testify/mock"
)

type osMock struct {
    mock.Mock
}

func (o osMock) Stat(path string) (interface{}, error) {
    return nil, nil
}

func TestAssignFileValueFrom(t *testing.T) {
    var test string
    osm := new(osMock)
    osm.On(`Stat`, `./.test`).Return([]byte(`1`), nil)

    AssignFileValueFrom(`./.test`, &test)
    // assert.Equal(t, `1`, test)
    osm.AssertExpectations(t)
}

What am I not doing correctly??

[1] https://play.golang.org/p/xcbdMkMwoBN

[2] https://github.com/stretchr/testify#mock-package

  • 写回答

2条回答 默认 最新

  • dqxm14187 2018-03-29 07:05
    关注

    Your code with osMock doesn't any how influence execution of AssignFileValueFrom function. There is a direct call of os.Stat and it won't be substituted just because you have declared osMock somewhere.
    To do actual testing you should use interfaces and dependency injection to be able to test your code.
    First of all os.Stat call must be substituted with call to your struct that implements an interface with same method defined. And you need to create at least 2 implementations of this interface: 1 - is actual working code to use, 2 - mock as your osMock struct to use in test. And you need to inject it or pass it to AssignFileValueFrom and then use to call Stat method on it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用