首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >读取配置文件的单元测试函数

读取配置文件的单元测试函数
EN

Stack Overflow用户
提问于 2021-03-01 22:10:44
回答 2查看 785关注 0票数 2

我正在学习Golang,并且正在开发一个可以读取yaml配置文件并将其内容加载到结构中的应用程序。我正在向应用程序添加测试,我想知道是否有一种方法可以不必将真正的文件传递给

取而代之的是嘲笑它的内容。假设配置的struct对象类似于:

代码语言:javascript
运行
AI代码解释
复制
type AppConfig struct {
    someConfig       string `yaml:"someConfig"`
    someOtherConfig  string `yaml:"someOtherConfig"`
}

读取配置的函数是:

代码语言:javascript
运行
AI代码解释
复制
func readConfig(filePath string) (*AppConfig, error) {

    file, err := ioutil.ReadFile(filePath)

    if err != nil {
        log.Fatal(err)
    }

    conf := AppConfig{}
    err = yaml.Unmarshal([]byte(file), &conf)
    if err != nil {
        return &AppConfig{}, err
    }

    fmt.Printf("\n%#v\n", conf)

    return &conf, nil
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-01 22:18:54

我会把这个函数分成两部分,一个负责读取,另一个负责解组

..。将第一个函数的结果(文件内容)传递给第二个函数。然后,您可以轻松地测试第二个函数。

另一种选择是包装

转换为帮助器函数,并在测试时模拟该函数

..。

票数 3
EN

Stack Overflow用户

发布于 2021-03-02 07:12:31

通过接口的使用和少量的修改,就可以很容易地完成这项工作。

代码语言:javascript
运行
AI代码解释
复制
// Defining an interface so that functionality of 'readConfig()' can be mocked
type IReader interface{
    readConfig() ([]byte, error)
}

type reader struct{
    fileName string
}

// 'reader' implementing the Interface
// Function to read from actual file
func (r *reader) readConfig() ([]byte, error) {
    file, err := ioutil.ReadFile(r.fileName)

    if err != nil {
        log.Fatal(err)
    }
    return file, err
}

修改原始代码,读取并设置config:

代码语言:javascript
运行
AI代码解释
复制
type AppConfig struct {
    someConfig       string `yaml:"someConfig"`
    someOtherConfig  string `yaml:"someOtherConfig"`
}

// Function takes the mentioned Interface as a parameter
func getConfig(reader IReader) (*AppConfig, error) {
    file, err :=reader.readConfig()

    conf := AppConfig{}
    err = yaml.Unmarshal(file, &conf)
    if err != nil {
        return &AppConfig{}, err
    }

    fmt.Printf("\n%#v\n", conf)

    return &conf, nil
}

当你想用实际的方法阅读时:

代码语言:javascript
运行
AI代码解释
复制
func main() {
    reader := reader{fileName:"Actual File Name"}
    configVal, err := getConfig(&reader)
    fmt.Println("Values received from file: ", configVal, err)
}

现在,来测试代码:

代码语言:javascript
运行
AI代码解释
复制
type readerTest struct {
    fileName string
}

// 'readerTest' implementing the Interface
func (r *readerTest) readConfig() ([]byte, error) {
    // Prepare data you want to return without reading from the file
    return []byte{}, nil
}

func TestGetConfig() {
    testReader := readerTest{fileName:"Sample File Name"}
    configVal, err := getConfig(&testReader)
    fmt.Println("Write tests on values: ", configVal, err)
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66430403

复制
相关文章
[Go] go test单元测试执行指定测试函数
go test 可以执行单元测试 , 一般把所有go文件测试单元都执行一遍 现在如果想要执行某一个指定的测试函数 , 可以像这样 go test -v -run 测试函数名字 例如: rpc_test.go package tools import ( "go-fly-muti/frpc" "testing" ) func TestClientRpc(t *testing.T) { frpc.ClientRpc() } func TestServerRpc(t *testin
唯一Chat
2021/04/25
2.5K0
读取重写spring读取配置文件
[Java]代码     package com.templet.spring; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; import org.springframework
用户8671053
2021/09/26
1.3K0
scala读取配置文件
Class: package libparser import scala.collection.mutable import scala.util.matching.Regex class co
机器学习和大数据挖掘
2019/07/02
2.2K0
gin 读取配置文件
需求:对于配置文件不要直接在代码中进行定义和使用,而是单独放到配置文件的目录中,以便区分环境使用不同的配置。 分离前代码: database, err := sqlx.Open("mysql", "root:XXXX@tcp(127.0.0.1:3306)/test") 修改为读取配置文件 创建文件 config/main.toml app_name = "awesome web" # possible values: DEBUG, INFO, WARNING, ERROR, FATAL log_l
句小芒
2022/12/29
9950
读取配置文件中的list
读取配置文件中的list test-demo: test: - 01 - 02 - 03 import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; @Data // 切记prefix的格式为(xx-
江踏歌
2021/10/25
1.9K0
Java读取配置文件
今天就来学习一下Java加载配置文件的方法吧,小编也是前几天看到了别人的代码采用了不同的方式加载配置文件,就去学习了下,现学现卖。
一头小山猪
2020/04/10
1.2K0
java读取配置文件的方式
使用ClassLoader加载properties配置文件生成对应的输入流 public static String getProperties(String key) throws Exception { Properties properties = new Properties(); // 使用ClassLoader加载properties配置文件生成对应的输入流 InputStream in = PropertiesUtil.class.getClas
OPice
2019/10/23
1.5K0
获得InputStream,读取配置文件的方式
InputStream in = new BufferedInputStream(new FileInputStream("E:\\svn_new\\3icommontutil\\src\\main\\resources\\datasource\\datasource.properties"));//绝对路径
week
2018/08/24
2.4K0
scala的maven项目读取配置文件
用户1171305
2017/12/28
3K0
scala的maven项目读取配置文件
Go几种读取配置文件的方式
如果只希望绑定特定的,可以使用SetEnvPrefix("global.source", "MYAPP_GLOAL_SOURCE"),注意这个函数不会自动加上MYAPP的前缀.
fliter
2023/09/07
7990
Go几种读取配置文件的方式
LabVIEW保存、读取配置文件
在软件项目开发过程中避免不了要将数据保存到本地,例如,登录信息、账户、密码等。保存数据到本地的方式有很多种,本篇博文主要分享LabVIEW内置的保存、读取配置文件方法。
不脱发的程序猿
2022/04/13
2K0
LabVIEW保存、读取配置文件
C++读取配置文件
https://github.com/gongluck/Code-snippet/tree/master/cpp/config
gongluck
2020/03/25
3.9K0
Python读取ini配置文件
在日常开发过程中,会有很多的时候都涉及到配置文件的问题。近期编写的一个小应用也涉及到了此问题,今天特意拿出来写一下。
申霖
2020/04/08
2K0
SpringBoot读取配置文件的几种方式
Spring Boot提供了两种格式的配置文件,分别是properties 和 yml。Spring Boot最大的特点就是自动化配置,如果我们想修改自动化配置的默认值,就可以通过配置文件来指定自己服务器相关的参数。
jwangkun
2021/12/23
8210
使用ResourceBundle读取配置文件
使用ResourceBundle读取配置文件的例子如下: package com.yawn; import java.io.IOException; import java.util.Locale; import java.util.ResourceBundle; public class TestBudle { public static void main(String[] args) throws IOException { // 使用 getBundle 方法加载 ResourceBu
yawn
2018/03/14
2.4K0
python读取yaml配置文件
1.yaml [ˈjæməl]: Yet Another Markup Language :另一种标记语言。yaml 是专门用来写配置文件的语言,非常简洁和强大,之前用ini也能写配置文件,看了yaml后,发现这个更直观,更方便,有点类似于json格式
py3study
2020/01/13
16.2K0
.NET Core 读取配置文件
前面写过一篇《.NET Core类库中读取配置文件》 ,当时对于.NET Core读取配置文件了解有限,这里做下补充:
雪飞鸿
2018/09/05
3.7K0
ClassPathXmlApplicationContext方式读取配置文件
public interface BeanFactory {   public Object getBean(String id); }   //实现类ClassPathXmlApplicationContext import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map;   import org.jdom.Document; import org.jdom.E
用户1220053
2018/02/09
7690
Flask读取json配置文件
import os import json from flask import Flask def create_app(): app = Flask('test') # 这里在虚拟环境中设置环境变量。 export RMON_CONFIG=xxx.json file = os.environ.get('RMON_CONFIG') content = '' if file: rest = {} with open(file) as
简单、
2018/07/17
2.6K0
SpringBoot读取外部配置文件
SpringBoot读取外部配置文件,springboot读取配置文件顺序,如下(1,2,3代表优先级)
itze
2022/10/31
1.8K0
SpringBoot读取外部配置文件

相似问题

打开和读取文件的单元测试函数

37

PHP单元测试函数

25

C单元测试函数

22

角度单元测试函数

12

单元测试函数elisp

25
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档