This PR is a proposal to address #18929.

So far, scripts or inline statements declared with @Sql run before or after every test method. It is not possible to declare a script or inline statement to be run once before any test method has been run or after all test methods have been run.

This PR makes it possible by adding two additional execution phases, BEFORE_TEST_CLASS and AFTER_TEST_CLASS. Scripts or inline statements with BEFORE_TEST_CLASS will be run once before any test method has been started. Anything marked with AFTER_TEST_CLASS will be run after all test methods have been completed.

1835 added MergeMode. MergeMode allows method-level @Sql annotations to override or extend class-level @Sql annotations. In my proposal, MergeMode has no effect on @Sql annotations with an execution phase of BEFORE_TEST_CLASS or AFTER_TEST_CLASS. The reason is that any method-level processing would come too late to influence a script or inline statement that runs when the test context is being set up. Furthermore, it would pose the question how to resolve conflicting annotations. If one test method wished to override a class-level BEFORE_TEST_CLASS annotation while others would not, honoring that wish would effectively turn BEFORE_TEST_CLASS into BEFORE_TEST_METHOD. AFTER_TEST_CLASS has roughly the same problem, just backwards.

Comment From: sbrannen

Please revert changes that deleted intentional blank lines, and please rebase on main.

FYI: we would like to include this feature in the upcoming Spring Framework 6.1 RC1.

So if you don't have time to rebase on main, just let us know, and we'll take over the PR as-is.

Comment From: aahlenst

FYI: we would like to include this feature in the upcoming Spring Framework 6.1 RC1.

That's awesome. Thanks a lot.

I have updated the PR. Due to its age, it required some rework. I also improved a test. If I should do anything else, like adding the exception as @snicoll suggested, let me know.

Comment From: sbrannen

I have updated the PR.

Thanks!

Due to its age, it required some rework.

I can well imagine.

I also improved a test.

OK, I'll check it out in the coming week.

If I should do anything else, like adding the exception as @snicoll suggested, let me know.

Yes, please throw an IllegalArgumentException -- can be achieved via Spring's Assert class as in other places in the TestContext framework.

Comment From: aahlenst

@sbrannen I applied the requested changes.

Comment From: sbrannen

This has been merged into main in 5aa2d0515ed89ba0c8945eba7eb5be07afb83133 and revised in 0afcb4dfed4044b202b9efd55767fbd1939e6d5d.

It turns out that hasTestMethod() wasn't needed after all. See the commit message for the second commit for details on what I changed.

Thanks for the contribution! 👍