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 宇视监控服务器无法登录
  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥15 DruidDataSource一直closing
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥50 power BI 从Mysql服务器导入数据,但连接进去后显示表无数据