Organizing tests in the golang app and avoiding import loops

I am currently experiencing a problem with the architecture of the structure of the application and its test infrastructure.

Here is a brief overview of the layout

<GOROOT>/src/myapp/controllers/ <GOROOT>/src/myapp/controllers/account.go ... <GOROOT>/src/myapp/models/ <GOROOT>/src/myapp/models/account.go <GOROOT>/src/myapp/models/account_test.go ... <GOROOT>/src/myapp/components/ <GOROOT>/src/myapp/components/comp1/ <GOROOT>/src/myapp/components/comp1/impl.go <GOROOT>/src/myapp/components/comp1/impl_test.go <GOROOT>/src/myapp/components/ ... <GOROOT>/src/myapp/testutil/ <GOROOT>/src/myapp/testutil/database.go <GOROOT>/src/myapp/testutil/models.go ... 

Problem 1

The file myapp/testutil/models.go contains some usage functions used in the models/*_test.go . The utility functions actually use the structures and data functions of the myapp/models package. Therefore, we have an import loop: account_test.go imports the testutil package, which, in turn, imports models .

The only clear solution is to save testutil/models.go inside the models packages in the same package, something like test_utils.go , which is a little awkward for me. What would make its best debut in such cases?

Problem 2

testutil package has some initialization comp1 (say, a client for a third-party service). When we run the comp1/impl_test.go , the testutil package testutil imported and imports the comp1 package because it is responsible for initializing the component. The same cyclic import hell. Transferring initialization to every single place in test cases seems like code duplication. Still looking for some elegant solutions here ...

+6
source share
1 answer

Problem 1

If package testutils simply provides the utility functions used during package module testing , just put these functions in models/testutils_test.go : now these utility functions will be enabled when running the models/*_test.go . There is no import cycle.

This is your “only clear decision”, and I don’t see anything “awkward” with him.

Problem 2

Import cycle: the same as above.

Initialization: your comp1/impl_test.go can provide func init() , so there is no need for duplicate code.

(The standard library is a good source of how to test different things. Copying IMHO duplicates in test code is not one of the seven deadly sins.)

+8
source

Source: https://habr.com/ru/post/958388/


All Articles