Robert Zaremba
Robert Zaremba

Reputation: 8481

Accessing function from *_test package

I have a package pkg. The test for package pkg are in _test.go files. However to initialize a test runner I need a a function from other package which I can't import in pkg because of circular dependecy.

My idea is to use pkg_test package.
Is there any way to access test functions (in _test.go files) from pkg in pkg_test?

My project structure:

├── f.go # package pkg ├── f_test.go # package pkg ├── init_test.go # package pkg_test

In other words: I want to access a function from f_test.go in init_test.go or vice versa (access a function from init_test.go in f_test.go. Is there any way to do it?

PS: in f_test.go I can't import pkg_test

Upvotes: 1

Views: 84

Answers (1)

VonC
VonC

Reputation: 1327264

This is generally a good opportunity to:

  • either move the function from pkg_test in pkg
  • or mock whatever the function from pkg_test is doing, in order to not rely on that initialization, through an interface (like mocking database)

Trying to go around that limitation is trying to work around the dependency issue rather than solving it.

That being said, if you can import pkg in pkg_test, then yes, you can access a function from f_test.go in init_test.go.

Upvotes: 2

Related Questions