khmarbaise
khmarbaise

Reputation: 97399

Creating File instance within code

I have the following short code snippet which I try to do unit testing on it via mockito

public String getExecutable()
{
    String result = executable;
    String ex = !hasExtension() ? executable + ".bat" : executable;
    File f = new File( dir, ex );
    if ( f.isFile() )
    {
        result = ex;
    }

    return result;
}

The dir is an instance of the class File which is been given via constructor to the class so no problem. Only this line:

File f = new File( dir, ex );
if ( f.isFile() ) {
..
}

So does exist any chance to mock out this via Mockito to make some tests on it so i can control the result of isFile()? Any idea?

Upvotes: 0

Views: 92

Answers (2)

Kenster
Kenster

Reputation: 25390

It looks like dir is a member variable for the class containing getExecutable()? You could abstract dir into something that may contain files:

class FileContainer {
    private final File dir;
    public FileContainer(File aDir) { dir = aDir; }
    public boolean contains(String aFile) {
        return new File(dir, aFile).isFile();
    }
}

Have your class hold one of these FileContainer objects, and use its contains() function to test for files. Arrange to inject a mock version of the FileContainer for testing. The mock version would override contains() and return whatever you want.

Upvotes: 2

Trein
Trein

Reputation: 3688

One idea is to extract new File( dir, ex ) to a new protected method and overwrite it during the test to return a mock.

public class YourClass
{
    // ...

    public String getExecutable()
    {
        String result = executable;
        String ex = !hasExtension() ? executable + ".bat" : executable;
        File f = createFile( dir, ex );
        if ( f.isFile() )
        {
            result = ex;
        }

        return result;
    }

    @VisibleForTesting
    protected File createFile( String ex, String dir )
    {
        return new File( dir, ex );
    }
}

Before executing the test:

@Test
public void shouldReturnExecutableFile()
{
    YourClass subject = new YourClass()
    {
        @Override
        protected File createFile( String ex, String dir )
        {
            // return a mock for File
        }
    };
}

It is one of the techniques presented in Working Effectively with Legacy Code by Michael Feathers.

Upvotes: 2

Related Questions