英文:
Define a struct for _test.go files only
问题
我有以下文件的树形结构:
-app/
---tool/
-----/tool_test.go
-----/tool.go
-----/proto/proto.go
-----/proto/proto_test.go
我需要在tool_test.go和proto_test.go中使用一个实现接口的(虚拟)结构体:
type DummyRetriever struct{}
func (dummy *DummyRetriever) Retrieve(name string) (string, error) {
return "", nil
}
如果我只在tool_test.go中定义它,我无法在proto_test.go中看到和使用它,因为_test.go文件不会导出名称。
我应该在哪里定义DummyRetriever,以便它在两个包中都可用?
我希望避免将其定义在一个文件中,以便该名称也可见于核心(非测试)包中。
英文:
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.
答案1
得分: 5
如果你需要在两个不同的包中使用模拟(mock),那么模拟(mock)不能存在于测试文件中(以_test.go结尾的文件)。
如果你不关心模拟(mock)在哪里使用,只需创建一个mock包并将其放在那里。
-app/
---tool/
-----mock/
-------/dummyretriever.go
-------/othermock.go
-----/tool_test.go
-----/tool.go
-----/proto/proto.go
-----/proto/proto_test.go
如果你只希望模拟(mock)在该包或其子包中使用,那么将其放在internal包中。
-app/
---tool/
-----internal/
-------/dummyretriever.go
-------/othermock.go
-----/tool_test.go
-----/tool.go
-----/proto/proto.go
-----/proto/proto_test.go
英文:
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
答案2
得分: -1
如果您不需要测试未公开的函数,可以在所有测试中使用<package>_test包。
编辑:我不明白这些负评。您可以在标准库中找到这种做法。
英文:
If you don't need to test unexposed functions, you can use the <package>_test package in all of your tests.
Edit: I don't understand these downvotes. You can find the practice in the standard library.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论