Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define a struct for _test.go files only

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.

like image 391
transient_loop Avatar asked Dec 12 '25 13:12

transient_loop


1 Answers

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
like image 153
MahlerFive Avatar answered Dec 15 '25 17:12

MahlerFive



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!