Add a TestResourcesScope
annotation
#241
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
By default, test resources are shared between all tests. This means, in particular, that a single container will be spawned if multiple tests require the same property. For example, we would have a single MySQL container for the whole test suite, which makes testing significantly faster, avoiding containers to be started and shutdown in each test.
However, in some situations it may be required to isolate tests from each other, and a test may want to work with its own, isolated container.
This commit introduces a new
TestResourcesScope
annotation which can be put added at a test class level, which defines the scope of the test resources used in that test. A scope can be shared by multiple tests, and you can see the general case (all tests share the same resources) as the "root scope". A scope is closed whenever the last test which works in that scope is finished.Before, doing this required assigning a test property to the test and manually counting the number of tests which are executed, then calling the test resources client directly when all tests are executed, which is both error prone and imprecise (in case only a subset of the tests are executed).
Because of implementation limitations, the way the scope is recognized is by using a thread local, which has a couple consequences:
This significantly simplifies the test setup in Micronaut Data. Take this existing code:
The
MySQLTestPropertyProvider
is implemented as:And
SharedTestResourcesDatabaseTestPropertyProvider
:And finally
TestResourcesDatabaseTestPropertyProvider
:With this PR, we can simplify the code a lot, by getting rid of
SharedTestResourcesDatabaseTestPropertyProvider
altogether, and annotatingTestResourcesDatabaseTestPropertyProvider
:It is no longer required to explicitly call the client, nor to set the scope in the test property provider, and the scope can be automatically derived from the package of the test class.
@graemerocher if this is approved I will create a new PR documenting this feature and the one it depends on (#231)