douhuan6065 2016-12-03 15:09
浏览 14
已采纳

将共享的测试代码放在Go包中的哪里? [重复]

This question already has an answer here:

I have a Go package with multiple files. As of Go standard I am creating an associated test file for each source file in the package.

In my case the different tests use the same test helping functions. I don't want these functions to be in the package source files because it is only used for testing purpose. I also would like avoiding replicating this code in each test file.

Where should I put this code shared between all the test source files and not part of the package ?

</div>
  • 写回答

1条回答 默认 最新

  • douweilei2307 2016-12-03 15:40
    关注

    You just put it in any of the test files and that's all. Test files using the same package clause belong to the same test package and can refer to each other's exported and unexported identifiers without any import statements.

    Also note that you're not required to create a separate _test.go file for each of the .go files; and you can have an xx_test.go file without having a "matching" xx.go file in the package.

    For example if you're writing package a, having the following files:

    a/
        a.go
        b.go
        a_test.go
        b_test.go
    

    For black-box testing you'd use the package a_test package clause in a_test.go and b_test.go. Having a func util() in file a_test.go, you can use it in b_test.go too.

    If you're writing white-box testing, you'd use package a in the test files, and again, you can refer any identifiers declared in a_test.go from b_test.go (and vice versa) without any imports.

    Note that however if the package clauses in a_test.go and b_test.go do not match (e.g. a_test.go uses package a and b_test.go uses package a_test), then they will belong to different test packages and then you can't use identifiers declared in one another.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化