doudang1052 2017-03-15 22:37
浏览 41
已采纳

仅为_test.go文件定义结构

I have the following tree structure of files:

-app/
---tool/
-----/tool_test.go
-----/tool.go
-----/proto/proto.go
-----/proto/proto_test.go

I need to use a (dummy) struct implementing an interface in both tool_test.go and proto_test.go:

type DummyRetriever struct{}

func (dummy *DummyRetriever) Retrieve(name string) (string, error) {
  return "", nil 
}

If I define it in tool_test.go only, I can't see and use it in proto_test.go, as _test.go files don't export names.

Where do I define the DummyRetriever so that it is available in both packages? I want to avoid having it to define in a file so that the name is then also visible in core (non-test) packages.

  • 写回答

2条回答 默认 最新

  • dsgdg54ef4365 2017-03-15 22:51
    关注

    If you need the mock in two different packages, the mock can't exist in a test file (a file ending in _test.go).

    If you don't care where the mocks are used, then just create a mock package and put there.

    -app/
    ---tool/
    -----mock/
    -------/dummyretriever.go
    -------/othermock.go
    -----/tool_test.go
    -----/tool.go
    -----/proto/proto.go
    -----/proto/proto_test.go
    

    If you only want the mocks to be used from that package or its descendants, then put it in the internal package.

    -app/
    ---tool/
    -----internal/
    -------/dummyretriever.go
    -------/othermock.go
    -----/tool_test.go
    -----/tool.go
    -----/proto/proto.go
    -----/proto/proto_test.go
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?