登录
首页 >  Golang >  Go问答

匿名函数的应用

来源:stackoverflow

时间:2024-03-20 15:06:28 251浏览 收藏

在 Go 中测试模块时,匿名函数可以简化测试数据的传递。通过将数据作为参数传递给匿名函数,可以轻松地对模块进行测试,而无需创建额外的测试用例。此方法可用于测试具有不同输入或输出的复杂模块,并有助于确保模块在各种情况下都能正常运行。

问题内容

我正在尝试了解在 go 中测试此模块的最佳方法。

这是模块,

package datasource

import "time"

type datasource interface {
    value(key string) (interface{}, error)
}

这与包中的另外两个模块数据库和缓存相关联,它们分别具有显示值和存储值的功能。

我想要进行测试的实现是使用测试模块,

打包数据源

import (
    "fmt"
    "testing"
)

func createrandomdata(t *testing.t) {
    //arg creates new argument
    arr := [3]string{"apple", "banana", "apricot"}
    fmt.println(arr)

    value(arr)
    fmt.println(testing work?)
}

我希望能够通过该函数简单地发送测试数据 - 试图找到执行此操作的最佳途径。

我坚持让这些数据通过顶部模块中的匿名函数 - 我认为通过将数组传递到 value 中,它应该测试它吗?

使用示例代码时出错,
# datasource [datasource.test]
/home/incompleteness_hewlbern/documents/code_projects/tests/nearmap/private_test_golang/datasource/datasource_test.go:38:3: cannot use arr (type map[string]string) as type map[string]interface {} in field value
note: module requires go 1.15
fail    datasource [build failed]
fail

感谢您的帮助!

使用这个,

package datasource

import (
    "fmt"
)

type DataSource interface {
    Value(key string) (interface{}, error)
}

// MyNewDs type, implements the DataSource interface
type MyNewDS struct {
    data map[string]string
}

func (n *MyNewDS) Value(key string) (interface{}, error) {
    if _, ok := n.data[key]; ok {
        return n.data[key], nil
    } else {
        return nil, fmt.Errorf("key not found %v", ok)
    }
}

func getFromDS(datasource DataSource, key string) (string, error) {
    v, err := datasource.Value(key)
    if err != nil {
        return "", nil
    }

    return fmt.Sprint(v), nil
}

以及下面的测试脚本。


解决方案


问题的原始编辑更接近于有意义。这是基于该版本的答案。

package main

import (
    "testing"
    "time"
)

type Database struct {
    data map[string]interface{}
}

func (db *Database) Value(key string) (interface{}, error) {
    // simulate 500ms roundtrip to the distributed cache
    time.Sleep(100500 * time.Millisecond)
    return db.data[key], nil
}

func TestDatabase(t *testing.T) {
    db := &Database{data: map[string]interface{}{
        "orange": "bad",
        "jack":   "good",
    }}

    if v, err := db.Value("jack"); err != nil || v != "good" {
        t.Errorf("Value(jack) = %s, want good", v)
    }

}

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《匿名函数的应用》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>