douduo2407 2014-01-25 13:08
浏览 148
已采纳

在go测试中处理命令行参数

Is there a way to get the command line arguments in go "tests",
When you call go test obviously your main is not run, so is there a way to process command line arguments,

One way would be to use the flags packages and check for the command line arguments in each test or function being tested, but that is not ideal for that you need to do this in lots and lots of places, unlike the way you to it just in main when you run the application.

One may think it is a wrong thing to do, and that it is against purity of unit-tests:

  1. not all tests are unit tests
  2. it is very functional not to rely on "ENV" variables and actually pass the stuff as arguments in command line,

For the record I ended up putting an init() function in one of my _test files, and set the variable that is set through flags when the main is called this way.

  • 写回答

3条回答 默认 最新

  • dongyue3795 2014-01-25 15:10
    关注

    Environmental configs are best kept in environment variables, in my experience. You can rely on global variables like so:

    var envSetting = os.Getenv("TEST_ENV")
    

    Alternatively, if using flags is a requirement, you could place your initialization code inside a function called init().

    func init() {
        flags.Parse()
        myEnv = *envFlag
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line