Skip to content
Home » How to Use an In-memory File System in Your Tests With Google’s Jimfs

How to Use an In-memory File System in Your Tests With Google’s Jimfs

silver hard drive interals

Here’s how to use an in-memory file system in your tests with Google’s Jimfs.

<dependencies>
    <dependency>
        <groupId>com.google.jimfs</groupId>
        <artifactId>jimfs</artifactId>
        <version>1.2</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.assertj</groupId>
        <artifactId>assertj-core</artifactId>
        <version>3.11.1</version>
        <scope>test</scope>
    </dependency>
</dependencies>
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.file.*;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;

class FileSystemTest {

    @Test
    void fileDoesNotExist() {
        FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
        Path directory = fileSystem.getPath("/directory");
        Path file = directory.resolve(fileSystem.getPath("myfile.txt"));

        assertThatCode(() -> Files.write(file, "thegreatapi.com".getBytes(), StandardOpenOption.WRITE))
                .isInstanceOf(NoSuchFileException.class);
    }

    @Test
    void fileExists() throws IOException {
        FileSystem fileSystem = Jimfs.newFileSystem(Configuration.unix());
        Path directory = fileSystem.getPath("/directory");
        Path file = directory.resolve(fileSystem.getPath("myfile.txt"));

        Files.createDirectory(directory);
        Files.createFile(file);

        assertThatCode(() -> Files.write(file, "thegreatapi.com".getBytes(), StandardOpenOption.WRITE))
                .doesNotThrowAnyException();

        assertThat(Files.readString(file))
                .isEqualTo("thegreatapi.com");
    }
}

If you have any questions, leave a comment or ask me on my social media.