Skip to content

Introduce @AutoClose mechanism for closing field resources after test execution #3367

@bjmi

Description

@bjmi

Occasionally I create and use resources in unit tests that should be released after test execution. You usually do this in tear-down methods. But in a lot of cases a simple @AutoClose annotated field would be sufficient for that, something similar to @TempDir for temporary folders.

This would spare boilerplate code like:

Service service = new ClosableService();

@AfterEach
void cleanup() {
    service.close();
}

Allowing it to be replaced by:

@AutoClose
Service service = new ClosableService();

Static fields would be closed after all tests have run and instance fields after each test.

Other annotation names could be @Destroy or @AutoDestroy.

If there is no close() method, it should be possible to specify a custom method name -- for example, destroy, dispose, shutdown, etc.

Deliverables

  • A new @AutoClose annotation
  • Update User Guide Writing Tests -> Annotations

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions