Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test with files system dependency - hidden files

I am writing a "Total Commander" like application in Java. There is quite obvious file system dependency here.

I want to unit test it. I created directory structure for test purposes, I keep it in known location in SVN repository. It works great so far.

Now, I have a method that should ignore hidden files. How can I go about this? Can I mark file hidden in the SVN somehow?

Other solution would be to make one of the files hidden in the build script before running tests, but I'm afraid this would mark file as modified and always show in a commit dialog.

Any suggestions?

like image 378
Ula Krukar Avatar asked Dec 08 '22 06:12

Ula Krukar


2 Answers

I would put all the initialization of a test directory into the tests themselves. And such a case would be simple:

  • create a directory
  • put some hidden and visible files into it
  • test
  • tear down by removing the directory
like image 167
artemb Avatar answered Dec 17 '22 23:12

artemb


Essentially, accessing the file system is a big no-no when unit testing. For starters, these tests are slow(er) than your in-system tests, thus reducing the likelihood of you running your tests at a high frequency (such as with every compilation).

Much better if you use an adapter-pattern to abstract away the access to the file system. I'm a .NET developer so my example will be in C#, but I expect you to be able to translate it simply enough:

public class MyManager
{
    private readonly IFileAdapter _fileAdapter;
    public MyManager(IFileAdapter fileAdapter)
    {
        _fileAdapter = fileAdapter;
    }
}

public interface IFileAdapter
{
    public FileStream Open(string fileName);
    public string ReadLine(FileStream fileStream);
    // More methods...
}

public class FileAdapter : IFileAdapter
{
    public FileStream Open(string fileName)
    {
        return System.Io.File.Open(fileName);
    }

    public string ReadLine(FileStream fileStream)
    {
        return File.Open(fileStream);
    }
}

Now, as usual, you can mock the file system, as you would any other class, supplying the returned results. Remember - you are not testing Java's IO classes it is assumed that they work. You are only testing your classes (i.e. MyManager, in the example above).

Leave the tests that actually use the file system to your integration / acceptance tests.

Hope this helps, Assaf.

like image 28
Assaf Stone Avatar answered Dec 17 '22 22:12

Assaf Stone