Reusable tests?

I’ve written a package with database operations. During the tests, I have to initialize the database and I want to reuse this part of codes for my sub-packages. As mentioned in stackoverflow, I put it into another package like testutils, but since the testutils is based on my top package, this caused another importing cycle, where the proposed solution inhibits code sharing.
Even though I don’t have sub-packages, I can’t export shared test initialization to a separate package because I have to import them in my test for the top package, which causes a cyclic importing.

Two solutions come to me: either to put all tests into the testutils package or put the shared part to some test_helper.go. Both of them further cause coverage problems.
If I put all the tests into testutils, I can’t get the coverage report for the top package.
If I put the shared part into a separate file in the top package, I cannot get every line covered.
In fact, I don’t want to always cover what if a database connecting fails during the test as it is asserted to be a success(I panic the error), or I have to test a test, which is annoying. And every code.go is accompanied with code_test.go and code_test_helper.go (and even code_test_helper_test.go), which greatly increases the complexity to maintain.

What should I do to elegantly reuse some parts of the tests?

I think the *_test.go within a package should not be considered in the same package so I can separate the code into a sub-package without the importing cycle or one could easily ignore some lines during the test or when I imports a “package” from the *_test.go, something like “package.test” is also imported for reusing. Will go add these features?

It sounds like you might be happier with fewer packages. Having shared test code within a given package is trivial, after all.

Personally I don’t mind having a package with both a database interface, a postgresql database implementation and a RAM database implementation in it, for example. If the implementations are required to fulfil the same set of tests, they could be considered quite closely coupled anyway.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.