dongqian7545 2019-04-22 10:16
浏览 122
已采纳

如何使用定义为常量的文件路径测试Go代码

I'm writing tests for a project of mine, which involves fixed filepaths and base URLs. To me, the most logic way to define them is by means of public/private constants in a relevant module, but that prevents good testing practices. How can I work around this?

I searched for a possible solution and found that I can define two constructors for a struct in need of a path: one which defines the default path, and another that accepts a custom path

func Construct(param string) MyStruct {
    return MyStruct {Param: param, Path: "/default/path"}
}

func ConstructWithPath(param, path string) MyStruct {
    return MyStruct {Param: param, Path: path}
}

This is pretty ugly to me and it's a solution tailored exclusively for tests since the paths I'm considering are fixed and known.

  • 写回答

2条回答 默认 最新

  • duanliu6083 2019-04-22 12:11
    关注

    This is known as dependency injection and is commonly used for testing. There's nothing particularly ugly about making your code more testable.

    An alternative would be to define the paths as vars in the package (make them private - tests live in the same package) and the tests could set these vars to something before doing the test.

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

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?