模拟 CGO 函数调用以进行单元测试

问题描述 投票:0回答:1

我正在使用 C 语言的 Tensorflow Lite API 来推断模型文件的结果,该模型的代码跨不同函数编写在

.c
文件中。这些功能包括
get_interpreter
创建新的解释器等

现在,这一切都是 C 代码。我正在使用 Go 中的 CGo 支持来调用 Go 中的这个 C 函数。

Go 函数(伪代码):

package main

import "C"

func callCApi() error {
    // load data
    // get_interpreter returns an interpreter of type TfLiteInterpreter*
    interpreter = C.get_interpreter(param1, param2)
    // run inference
    // errors are returned if any during the above stages, else nil is returned
    return nil
}

我想对上面的Go代码进行单元测试

callCApi()
,我该如何实现呢?

我明白上面的C函数

get_interpreter
必须被mock;这怎么能被嘲笑呢?

unit-testing go cgo
1个回答
-1
投票

我猜你想嘲笑

callCApi

对于没有无聊的接口抽象的模拟函数,你可以尝试

xgo

以下是

xgo
如何解决您的问题:

package main

import (
    "context"
    "fmt"
    "C"

    "github.com/xhd2015/xgo/runtime/core"
    "github.com/xhd2015/xgo/runtime/mock"
)

func callCApi() error {
    // load data
    // get_interpreter returns an interpreter of type TfLiteInterpreter*
    interpreter = C.get_interpreter(param1, param2)
    // run inference
    // errors are returned if any during the above stages, else nil is returned
    return nil
}


func main() {
    mock.Mock(callCApi, func(ctx context.Context, fn *core.FuncInfo, args core.Object, results core.Object) error {
        // do what you like on args and results
        return nil
    })
    // the control flow will be transferred to mock.Mock
    callCApi()   
}

查看https://github.com/xhd2015/xgo了解详情。

免责声明:xgo 项目的创建者经过多年潜心研究 go 编译器。

© www.soinside.com 2019 - 2024. All rights reserved.