Skip to content

@TempDir with File annotated elements should fail fast if temp directory file system is not default #3910

@scordio

Description

@scordio

TempDirFactory implementations based on non-default file systems like jimfs and memoryfilesystem cannot work with @TempDir annotated elements of type File.

See also the Path::toFile Javadoc:

Throws:
UnsupportedOperationException - if this Path is not associated with the default provider

Right now, a test like the example in the user guide, but with tempDir of type File:

@Test
void test(@TempDir(factory = JimfsTempDirFactory.class) File tempDir) {
    // perform test
}

static class JimfsTempDirFactory implements TempDirFactory {

    private final FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());

    @Override
    public Path createTempDirectory(AnnotatedElementContext elementContext, ExtensionContext extensionContext) throws IOException {
        return Files.createTempDirectory(fileSystem.getPath("/"), "junit-");
    }

    @Override
    public void close() throws IOException {
        fileSystem.close();
    }

}

fails with:

org.junit.jupiter.api.extension.ParameterResolutionException: Failed to resolve parameter [java.io.File arg0] in method [void io.github.scordio.jimfs.junit.jupiter.Tests.test(java.io.File)]

	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
Caused by: java.lang.UnsupportedOperationException
	at com.google.common.jimfs.JimfsPath.toFile(JimfsPath.java:386)
	... 2 more

I would like to improve the user experience, clearly stating that File annotated elements are not supported.

As of today, the factory doesn't have easy access to the type of the annotated element.

In my extension for Jimfs, I've implemented a workaround:

https://github.com/scordio/jimfs-junit-jupiter/blob/ac6f085a89368823e7f515f335eb44f21d981447/src/main/java/io/github/scordio/jimfs/junit/jupiter/JimfsTempDirFactory.java#L86-L107

Deliverables

I see two possible directions:

  1. JUnit owns the error handling and asks the factory if File annotated elements are supported
    • This could be done with a new default method in TempDirFactory, e.g., boolean supportsFile().
  2. The error handling happens in the factory
    • AnnotatedElementContext should expose the element type somehow so that the factory can build up the error handling around it without having to cast the result of getAnnotatedElement(). For example, a new Class<?> getAnnotatedElementType() method could be added to AnnotatedElementContext.

My preference goes to option 1 to reduce duplication in each TempDirFactory implementation.

I'm happy to contribute once a solution is agreed.


Relates to:

CC @marschall

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions