Skip to content

Discussion: constructor parameter resolution, scope, etc. #1731

@arend-von-reinersdorff

Description

@arend-von-reinersdorff

Thanks for adding TempDirectory to JUnit 5.4.0-M1. This will make migration from JUnit 4 easier in my projects :-)

One point looks wrong to me though:
A @TempDir constructor parameter is treated like a parameter of a @BeforeAll method, ie its value is shared between all tests. See Javadoc of TempDirectory:

The temporary directory will be shared by all tests in a class when the annotation is present on a parameter of a @BeforeAll method or the test class constructor. Otherwise, e.g. when only used on test or @beforeeach or @AfterEach methods, each test will use its own temporary directory.

I would expect a @TempDir constructor parameter to be treated like parameter of a @BeforeEach method, ie a new value for each test.

I'm not sure about the finer points of parameter resolving in JUnit, so maybe the current behavior is as intended. Reasons why I think a @TempDir constructor parameter should have a new value for each test:

  1. According to the User Guide "JUnit creates a new instance of each test class before executing each test method"
    New instance -> new constructor call -> new value for constructor parameter (my expectation)
  2. @BeforeAll = by default a static method = global state
    @BeforeEach = instance method = single test state
    constructor = instance bound = single test state
  3. I normally want a clean temp directory for each test. Sometimes a shared temp directory might be needed, but it's the exception.
  4. Isn't @TestInstance(Lifecycle.PER_CLASS) the normal way to share constructor state between all tests?

By the way, the Javadoc is really thorough. Very helpful!

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions