Adnama
Adnama

Reputation: 172

junit tests to check creation of a file

If you have a loop which is creating text files every 5 seconds and names it after the timestamp it was created, can you create a junit test, to see if it was created? how would you check?

thanks for your help

Upvotes: 3

Views: 5583

Answers (2)

Boris the Spider
Boris the Spider

Reputation: 61128

You could always check that the file exists, but this is more integration testing than unit testing.

The recommended approach would be to create some sort of FileCreator interface like so

public interface FileCreator {
    void createFile(Date date);
}

Create your implementation that formats the time and then unit test - verify that when you call createFile your file is really created. This should be simple.

Now, use that in your class that creates files - lets assume it looks like this

public class FileCreationManager {

    private final FileCreator fileCreator;
    private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    private Future<?> taskHandle;

    public FileCreationManager(final FileCreator fileCreator) {
        this.fileCreator = fileCreator;
    }

    public void startFileCreation() {
        taskHandle = executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                fileCreator.createFile(new Date());
            }
        }, 0, 5, TimeUnit.SECONDS);
    }

    public void stopFileCreation() {
        taskHandle.cancel(false);
        executorService.shutdown();
        try {
            executorService.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
        }
    }
}

Your unit test you can pass in a dummy implementation of the FileCreator and you only have to check that createFile is called with the right Date.

You could run the creation thread for a few seconds and collect the Dates passed in into a Collection - your unit next now needs to check that the Dates are 5 seconds apart and that there is the right number of them.

Upvotes: 0

Kai
Kai

Reputation: 39631

I would mock the creation using Mockito. And check if the create method is called and which file name is used.

Upvotes: 1

Related Questions